Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 3 years have passed since last update.

ruby method化とclass化してみる.

Last updated at Posted at 2020-12-02

!Mac OS X-10.13.3 !ruby-2.7.0p0

前回の挨拶するプログラムを関数化したりclass化して見ます.

methodにする.

前回の名前を受け取って挨拶を表示した際,手順は'名前を受け取る'->'挨拶をする'だったので,今回はこれを勉強のために関数化します.

hello_method.rb
def get_name()
  name = ARGV[0]
  return name
end

これで,main文のところで呼び出すだけで名前をゲットできる.

name = get_name()

少し工夫して,入力がなければ世界に挨拶できるようにします.

hello_method.rb
def get_name() 
  name = ARGV[0] || "world"
  return name
end

次に挨拶のところを,関数化します.

hello_method.rb
def greeting(name)
puts "Hello #{name}."
end

これで完成.main文で

name = get_name()
greeting(name)

とすれば表示してくれる.

classにする

classにすると他のプログラムに持って行くときに楽になる.

今回は,上記で作った関数にmain文の内容をinitializeに書けばいいと思うのでそうする.

コードは

hello_class.rb
class Greeter
def initialize()
name = get_name()
greeting(name)
end

def get_name() 
  name = ARGV[0] || "world"
  return name
end

def greeting(name)
puts "Hello #{name}."
end
end

これで,main文にてclassを呼び出せばいい.

Greeter.new()

  • source ~/Github/grad_members_20f/members/yamatoken/items/class_and_method.org
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?