Return self (not nil) from Hash # [] when the key does not exist

Usually, when an element is passed to the hash without the corresponding key, the hash returns nil .

 hsh = {1 => "one", 2 => "two"} hsh[3] #=> nil 

I want to generate a hash that returns the value passed to it if there is no match.

 hsh[3] #=> 3 

I assume that the solution for this may include some kind of lambda ...?

** I am currently using a clumsy solution for this that uses a conditional method to prevent the transfer of inconsistent keys to the hash.

+4
source share
2 answers

If you only want to return the new values, but not add them:

  h = Hash.new { |_hash, key| key } 

To initially populate this hash, you can do:

  h.merge( {1 => "one", 2 => "two"} ) 

If the hash has already been created *:

  h.default_proc = proc do |_hash,key| key end #h[3] #=> 3 

* only in ruby ​​1.9 and higher

+8
source

Try the following:

 hsh.default_proc = proc do |hash, key| hash[key] = key end 

To return only the key, this is a trivial change:

 hsh.default_proc = proc do |hash, key| key end 
+1
source

Source: https://habr.com/ru/post/1498998/


All Articles