18
16

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.

Railsで引数を可変長で受ける

Last updated at Posted at 2015-07-03

Railsで extract_options! を利用すると、簡単に可変長で引数を受け取ることができます。こんな感じ。

def hoge(*args)
  options = args.extract_options!
  count = options[:count] || 1 # 存在しなかった時のデフォルト値
  hash = options[:hash] || {}
  
  p args
  p count
  p hash
end

hoge(1, 2, :count => 4, :hash => {"a" => 1, "b" => 2})
# => [1, 2]
# => 4
# => {"a"=>1, "b"=>2}

挙動的には引数のうちハッシュ形式で送ったものが、extract_options! を通すことで args から抽出されるのですが、上記の書き方だとハッシュ形式ではない引数が受け取りにくくなります(一つ目の引数を受け取るなら args[0] とアクセスしないといけない)。

なので、こう書いてみるのはどうでしょう。

def hoge(val1, val2, *args)
  args = args.extract_options!
  count = args[:count] || 1
  hash = args[:hash] || {}
  
  p val1
  p val2
  p count
  p hash
end

hoge(1, 2, :count => 4, :hash => {"a" => 1, "b" => 2})
# => 1
# => 2
# => 4
# => {"a"=>1, "b"=>2}

こんな風にハッシュ値で送るもの以外は変数を明示的に書くと、取り出しやすくなります。
必須項目はそのまま書いて、オプションとして受け取りたいものはハッシュで書くと気持ち可読性が上がるかもしれません。

18
16
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
18
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?