0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

自分用rubyメモ メソッドについて(随時追記)

0
Last updated at Posted at 2016-06-14

メソッドの使い方や多重代入等

method.rb
def hello
    p "Hello!"
end

def bye(name)
    p "bye,#{name}!"
end

def get_age
    20
end

def get_multi
    return 10,20
end

hello()
bye("daiki")
p get_age
a,b = get_multi
p a,b
result
"Hello!"
"bye,daiki!"
20
10
20

メソッドの分類

以下の3種類がある。

  1. インスタンスメソッド
  2. クラスメソッド
  3. 関数的メソッド

インスタンスメソッド

インスタンスをレシーバとするメソッド
"10,20,30".split(",")

クラスメソッド

クラスをレシーバとするメソッド
Array.new(Array::newという書き方もある)

関数的メソッド

レシーバに該当するものが無い(省略されているだけ)メソッド
print "Hello!"

メソッド定義や引数について

argument.rb
def hello(name="Ruby")   # デフォルト値に"Ruby"を設定しておく
    puts "Hello, #{name}."  # 注:複数の引数を持つ場合は、右端から順にデフォルト値を指定しないとだめ
end

hello()          # 引数を省略
hello("foo")

def three_loop
    for i in 1..3  # 何故かtimesメソッドだとエラーがでた。後日また検証する。
        yield
    end
end

num = 1
three_loop do
    print "#{num} "
    num *= 3
end
puts

def a(a,*b,c)  # 引数の数が不定な場合*を使用。今回は最低2つ引数が必要。
    [a,b,c]
end

p a(1,2,3,4,5)
p a(1,2)

def keyword_hash(a: 0,b: 0, c: 0, **args) # 引数リストに存在しないキーをもつハッシュオブジェクトが**をつけた変数に代入される
    [a,b,c,args]
end

p keyword_hash(a: 1,b: 2, c: 3, z: 4)

hash = {a: 1,b: 2, c: 3}
p keyword_hash(hash)         # ハッシュのキーとメソッドの引数の変数名が一致しているかチェックされる
result
Hello, Ruby.
Hello, foo.
1 3 9 
[1, [2, 3, 4], 5]
[1, [], 2]
[1, 2, 3, {:z=>4}]
[1, 2, 3, {}]

結論

  • returnが無くても最後の1行処理を戻り値として返す。
  • メソッドの戻り値を明示的にreturn foo,barとし、foo,bar = メソッドと呼び出す事で変数foo,barそれぞれに値が入る。
  • メソッドはレシーバによって3種類に分けられる。
  • キーワード引数を使うと使用可能なキーを制限したり、デフォルト値を与えたり出来る!
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?