塩焼きブログ

塩焼きに関しての研究内容を公開しています

Rubyのメソッドの引数を配列でまとめて渡す

配列に*を付けてmethod(*arr)と渡すことで引数に値が展開される。配列の要素数は引数と同じ数にする。

def profile(name, birthday, favorite_food)
  puts "name => #{name}"
  puts "birthday => #{birthday}"
  puts "favorite_food => #{favorite_food}"
end
profile("Mike", "1970-01-01", "apple")
# name => Mike
# birthday => 1970-01-01
# favorite_food => apple

arr = ["Jane", "1972-01-01", "strawberry"]
profile(*arr)
# name => Jane
# birthday => 1972-01-01
# favorite_food => strawberry

引数の数が合わなければエラーが発生する

arr = ["Jane", "1972-01-01"]
profile(*arr)
# example.rb:1:in `profile': wrong number of arguments (2 for 3) (ArgumentError)
#   from example.rb:18:in `<main>'

arr = ["Jane", "1972-01-01", "kiwi", "apple"]
profile(*arr)
# example.rb:1:in `profile': wrong number of arguments (4 for 3) (ArgumentError)
#   from example.rb:19:in `<main>'

一部の引数はそのまま渡し、残りを配列で渡すこともできる

arr = ["1972-01-01", "strawberry"]
profile("Jane", *arr)
# name => Jane
# birthday => 1972-01-01
# favorite_food => strawberry

arr = ["Jane", "1972-01-01"]
profile(*arr, "strawberry")
# name => Jane
# birthday => 1972-01-01
# favorite_food => strawberry

ハッシュで渡すことはできない

arr = [name: "Jane", birthday: "1972-01-01", food: "strawberry"]
profile(*arr)
# example.rb:1:in `profile': wrong number of arguments (1 for 3) (ArgumentError)
#  from example.rb:7:in `<main>'