I have a Hash in Ruby:
hash = Hash.new
It has some key value pairs in it, say:
hash[1] = "One"
hash[2] = "Two"
If the hash contains a key 2
, then I want to add "Bananas" to its value. If the hash doesn't have a key 2
, I want to create a new key value pair 2=>"Bananas"
.
I know I can do this by first checkng whether the hash has the key 2
by using has_key?
and then act accordingly. But this requires an if
statement and more than one line.
So is there a simple, elegant one-liner for achieving this?
Hash literals use the curly braces instead of square brackets and the key value pairs are joined by =>. For example, a hash with a single key/value pair of Bob/84 would look like this: { "Bob" => 84 }. Additional key/value pairs can be added to the hash literal by separating them with commas.
We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.
The key is sent to a hash function that performs arithmetic operations on it. The result (commonly called the hash value or hash) is the index of the key-value pair in the hash table.
This works:
hash[2] = (hash[2] || '') + 'Bananas'
If you want all keys to behave this way, you could use the "default" feature of Ruby's Hash:
hash = {}
hash.default_proc = proc { '' }
hash[2] += 'Bananas'
You could set the default value of the hash to an empty string, then make use of the << operator to concat whatever new values are passed:
h = Hash.new("")
#=> {}
h[2] << "Bananas"
#=> "Bananas"
h
#=> {2=>"Bananas"}
h[2] << "Bananas"
#=> "BananasBananas"
Per @rodrigo.garcia's comment, another side effect of this approach is that Hash.new()
sets the default return value for the hash (which may or may not be what you want). In the example above, that default value is an empty string, but it doesn't have to be:
h2 = Hash.new(2)
#=> {}
h2[5]
#=> 2
(hash[2] ||= "").concat("Bananas")
Technically, both your roads lead to the same place. So Hash[2] = "bananas"
produces the same result as first checking the hash for key 2. However, if you actually need the process of checking the hash for some reason a way to do that is use the .has_key?
method, and a basic if
conditional.
Suppose there is a hash,
`Hash = { 1 => "One", 2 => "Two" }`
setup a block of code based on the truth-value of a key search,
if hash.has_key?(2) == true
hash[2] = "bananas"
else
hash[2] = "bananas"
end
or more simply,
hash.has_key?(2) == true ? hash[2] = "bananas" : hash[2] = "bananas"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With