Pass hash to a function that accepts keyword arguments

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


As Stefan mentions, in Rails we have access to symbolize_keys that works like this:

{"band" => "for King & Country", "song_name" => "Matter"}.symbolize_keys
#=> {:band=>"for King & Country", :song_name=>"Matter"}

It's also aliased as: to_options, hence:

{"band" => "for King & Country", "song_name" => "Matter"}.to_options
#=> {:band=>"for King & Country", :song_name=>"Matter"}