Typically when an element is passed into a hash with no matching key, the hash returns nil
.
hsh = {1 => "one", 2 => "two"}
hsh[3] #=> nil
I want to form a hash that returns the value passed into it if there is no match.
hsh[3] #=> 3
I'm guessing that a solution for this might involve a lambda of some kind...?
** Right now I'm using a clumsy solution for this that uses a conditional method to prevent non-matching keys from being passed into the hash..
If you only want to return new values but not add them:
h = Hash.new { |_hash, key| key }
To initially populate this hash, you could do:
h.merge( {1 => "one", 2 => "two"} )
If the hash is already created*:
h.default_proc = proc do |_hash,key|
key
end
#h[3]
#=> 3
*only in ruby 1.9 and above
Try this:
hsh.default_proc = proc do |hash, key|
hash[key] = key
end
To return the key only, it's a trivial change:
hsh.default_proc = proc do |hash, key|
key
end
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