LoginSignup
5
4

More than 5 years have passed since last update.

Rubyで可変数の引数を複数取りたい場合のメソッド定義

Posted at

Rubyで可変数の引数を受け取りたい場合

def my_func(a, *x)
  p a, x
end

def my_func2(a, *x, b)
  p a, x, b
end

my_func(1)
#=> 1
#   []

my_func(1, 2 ,3 ,4)
#=> 1
#   [2, 3, 4]

my_func2(1, 2 ,3 ,4)
#=> 1
#   [2, 3]
#   4

のように書くことが出来ます。
my_func2では「一つ目は引数a」「最後は引数b」「それ以外は引数xとして配列で受け取る」と解釈してくれます。

しかし

def my_func3(a, *x, b, *y)
  p, a, x, b, y
end

という引数の変数は、自動で解釈することが不可能なので作れません。
このような引数を取る変数を作りたい場合は、以下のように作成します。

def my_func4(a, _x, b, _y)
  x = [_x].flatten
  y = [_y].flatten
  p a, x, b, y  
end

my_func4(1, 2, 3, 4)
#=> 1
#   [2]
#   3
#   [4]

my_func4(1, [2,3], 3, [4, 5])
#=> 1
#   [2, 3]
#   3
#   [4, 5]

5
4
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
4