LoginSignup
1
1

More than 5 years have passed since last update.

Ruby でキーワード引数として定義した引数群を Hash で得る方法を知りたい

Last updated at Posted at 2016-10-01

当然ながら、以下であれば普通に Hash として得られる。

def hoge(options = {})
end

def hoge(**kwargs)
end

問題は、以下だった時に {a: x, b: y, c: z} な形で引数群を参照したいのだけど、方法が分からないということ。これができる何かが用意されている様な気がするのだけど、分からない。

def hoge(a:, b:, c:)
end

Binding#local_variables を使うと以下の様に書く事ができる。 method(__method__).parameters を使う方法もある模様。

def hoge(a:, b:, c:)
  p Hash[binding.local_variables.map{ |_| [_, binding.local_variable_get(_)] }]
end
hoge(a: 1, b: 2, c: 3) # => {:a=>1, :b=>2, :c=>3}
1
1
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
1
1