[英]Add key-value for Ruby Hash from within the Hash
What's the best way to add a key-value pair to an hash object, from within the hash object itself? 从哈希对象本身内部向哈希对象添加键值对的最佳方法是什么?
The common way I know to add a new key to a hash is as follows: 我知道向哈希添加新键的常见方法如下:
hash = Hash.new
hash[:key] = 'value'
hash[:key] # => 'value'
What if I wan't to create a new hash which already has this key after its creation? 如果我不想创建一个在创建后已经具有此密钥的新哈希,该怎么办?
hash = Hash.new
hash[:key] # => 'value'
Is this possible? 这可能吗? Thanks!
谢谢!
To create a Hash with an already initialized set of values you can do: 要使用已初始化的一组值创建哈希,可以执行以下操作:
hash = { :key => 'value' }
hash[:key] # ===> This evaluates to 'value'
Just remember, the idiomatic way to create an empty hash in Ruby is: 请记住,在Ruby中创建空哈希的惯用方式是:
hash = {}
Not hash = Hash.new
like you exemplified. 不是
hash = Hash.new
就像您举例说明的那样。
Do you mean set the default value? 您的意思是设置默认值吗? is so, you could do with:
是的,您可以这样做:
hash = Hash.new('value')
hash[:key] # => 'value'
Not sure what you mean i the other answers aren't what you want, you can create a hash with some keys and values allready filled like this 不知道你的意思我其他答案不是你想要的,你可以创建一个哈希,其中已经填充了一些键和值,就像这样
hash = {:key => 'value'} #{:key=>"value"}
and like the others said, the default value for key's not allready present is given by passing a block tot the hash at creation time like 就像其他人说的那样,密钥尚未全部存在的默认值是通过在创建时将哈希传递给块的方式给出的,例如
hash = Hash.new('value') #{}
hash[:test] #"value"
or 要么
h = Hash.new { |hash, key| hash[key] = "Go Fish: #{key}" } #{}
h[:test] #"Go Fish: test"
Thje last sample teken from http://www.ruby-doc.org/core-1.9.3/Hash.html 最后一个样本来自http://www.ruby-doc.org/core-1.9.3/Hash.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.