将哈希传递给接受关键字参数的函数

时间:2015-02-26 15:46:42

标签: ruby hash kwargs

我有一个像hash = {"band" => "for King & Country", "song_name" => "Matter"}这样的哈希和一个类:

class Song
  def initialize(*args, **kwargs)
    #accept either just args or just kwargs
    #initialize @band, @song_name
  end
end

我想传递hash作为关键字参数,例如Song.new band: "for King & Country", song_name: "Matter"是否可能?

2 个答案:

答案 0 :(得分:10)

您必须将哈希中的键转换为符号:

class Song
  def initialize(*args, **kwargs)
    puts "args = #{args.inspect}"
    puts "kwargs = #{kwargs.inspect}"
  end
end

hash = {"band" => "for King & Country", "song_name" => "Matter"}

Song.new(hash)
# Output:
# args = [{"band"=>"for King & Country", "song_name"=>"Matter"}]
# kwargs = {}

symbolic_hash = hash.map { |k, v| [k.to_sym, v] }.to_h
#=> {:band=>"for King & Country", :song_name=>"Matter"}

Song.new(symbolic_hash)
# Output:
# args = []
# kwargs = {:band=>"for King & Country", :song_name=>"Matter"}

在Rails / Active Support中有Hash#symbolize_keys

答案 1 :(得分:0)

正如Stefan所提到的,在Rails中,我们可以访问symbolize_keys,其工作方式如下:

{"band" => "for King & Country", "song_name" => "Matter"}.symbolize_keys
#=> {:band=>"for King & Country", :song_name=>"Matter"}

它的别名也为:to_options,因此:

{"band" => "for King & Country", "song_name" => "Matter"}.to_options
#=> {:band=>"for King & Country", :song_name=>"Matter"}