[英]Add key-value for Ruby Hash from within the Hash
从哈希对象本身内部向哈希对象添加键值对的最佳方法是什么?
我知道向哈希添加新键的常见方法如下:
hash = Hash.new
hash[:key] = 'value'
hash[:key] # => 'value'
如果我不想创建一个在创建后已经具有此密钥的新哈希,该怎么办?
hash = Hash.new
hash[:key] # => 'value'
这可能吗? 谢谢!
要使用已初始化的一组值创建哈希,可以执行以下操作:
hash = { :key => 'value' }
hash[:key] # ===> This evaluates to 'value'
请记住,在Ruby中创建空哈希的惯用方式是:
hash = {}
不是hash = Hash.new
就像您举例说明的那样。
您的意思是设置默认值吗? 是的,您可以这样做:
hash = Hash.new('value')
hash[:key] # => 'value'
不知道你的意思我其他答案不是你想要的,你可以创建一个哈希,其中已经填充了一些键和值,就像这样
hash = {:key => 'value'} #{:key=>"value"}
就像其他人说的那样,密钥尚未全部存在的默认值是通过在创建时将哈希传递给块的方式给出的,例如
hash = Hash.new('value') #{}
hash[:test] #"value"
要么
h = Hash.new { |hash, key| hash[key] = "Go Fish: #{key}" } #{}
h[:test] #"Go Fish: test"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.