Pass hash to a function that accepts keyword arguments

hash, keyword-argument, ruby

Solution

You have to convert the keys in your hash to symbols:

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

In Rails / Active Support there is `Hash#symbolize_keys`

Problem

I have a hash like this `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 want to pass the `hash` as keyword arguments like `Song.new band: "for King & Country", song_name: "Matter"` Is it possible?

Original source