我有一个这样的hashhash = {"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"是否可能?

最佳答案

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

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

在导轨/主动支架中有Hash#symbolize_keys

关于ruby - 将哈希传递给接受关键字参数的函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28746767/

10-09 12:31