Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return self (rather than nil) from Hash#[] when key doesn't exist

Tags:

ruby

hash

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..

like image 894
boulder_ruby Avatar asked Jan 12 '23 13:01

boulder_ruby


2 Answers

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

like image 191
AShelly Avatar answered Feb 02 '23 06:02

AShelly


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
like image 33
Benjamin Tan Wei Hao Avatar answered Feb 02 '23 06:02

Benjamin Tan Wei Hao