微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby – 将哈希传递给接受关键字参数的函数

我有像这样的哈希= {“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

原文地址:https://www.jb51.cc/ruby/270501.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐