将散列传递给接受关键字参数的函数

Pass hash to a function that accepts keyword arguments

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

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" 这可能吗?

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

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/主动支持中有Hash#symbolize_keys

正如 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"}