"for King & Country", "song_name" => "Matter"} and a cl...">

Pass a hash to a function that takes keyword arguments

I have a hash like hash = {"band" => "for King & Country", "song_name" => "Matter"} and a class:

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

I would like to pass the hash arguments as a keyword like Song.new band: "for King & Country", song_name: "Matter" Is this possible?

+8
ruby kwargs hash
source share
1 answer

You need to convert the keys in your hash to characters:

 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 has Hash#symbolize_keys

+10
source share

All Articles