41
27

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.

可変長引数を引き回す

Last updated at Posted at 2013-02-06

可変長引数を引き回したい場合,
つまり可変長引数を受け取るメソッド内で,受け取った引数を他のメソッド(こちらも可変長引数を受け付ける)にしたいとき,少し注意が必要なことをいつも忘れるのでメモ.

def foo(*args)
  p args
end

def bar(*args)
  foo(args)
end

def hoge(*args)
  foo(*args)
end

実行結果は以下のとおり

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

この結果を見れば明らかで,可変長引数を受け取った後の(アスタリスクのついていない) args は配列なので,
一回展開してから渡さないと,もう一回り配列にくるまれちゃうということ.

要するに簡単にまとめると,可変長引数を可変長引数のまま引き回すには受け取り側も呼び出し側もアスタリスクをつければよい,ということ,なはず.

41
27
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
41
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?