LoginSignup
5
5

More than 5 years have passed since last update.

可変長引数を定義して、引数を渡さないとメソッド内では空配列になる。

Posted at

タイトルの通りです。
可変長引数の引数に配列を渡した時に、*を付けなかった場合と付けた場合で試してみました。

①で b.inspect が空配列になっています。

① *を付けなかった場合

可変長引数*bには値が渡されていません。

def foo(a, *b)
  puts "a:#{a.inspect}, b:#{b.inspect}"
end

data = [1, 2, 3]
foo(data)
結果
a:[1, 2, 3], b:[]

② *を付けた場合

可変長引数*bに、配列[2, 3]が渡されています。

def foo(a, *b)
  puts "a:#{a.inspect}, b:#{b.inspect}"
end

data = [1, 2, 3]
foo(*data)
結果
a:1, b:[2, 3]

補足

inspectじゃなくても同じでした。

def foo(a, *b)
  puts "a:#{a}, b:#{b}"
end

data =[1, 2, 3]
foo(data)
foo(*data)
結果
a:[1, 2, 3], b:[]
a:1, b:[2, 3]
5
5
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
5
5