我有像这样的哈希= {“band”=> “for King& Country”,“song_name”=> “物质”}和一个类:
class Song def initialize(*args,**kwargs) #accept either just args or just kwargs #initialize @band,@song_name end end
我希望将散列作为关键字参数传递,如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 / Active Support中有Hash#symbolize_keys