简体   繁体   中英

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:

hash = {}

Not hash = Hash.new like you exemplified.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM