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

mar*_*iya 9 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
Run Code Online (Sandbox Code Playgroud)

我想传递hashas关键字参数,如果Song.new band: "for King & Country", song_name: "Matter"它可能吗?

Ste*_*fan 12

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

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"}
Run Code Online (Sandbox Code Playgroud)

在Rails/Active Support中有 Hash#symbolize_keys