A custom message in which the key is not in the hash

By definition, ruby ​​hashes return zero when there is no key. But I need to use a special message instead of zero. Therefore, I use something like this:

val = h['key'].nil? ? "No element present" : h['key']

But this has a serious flaw. If in this case a value of nil is assigned against the key, then "No element present" will also be returned.

Is there any way to achieve this flawlessly?

thank

+3
source share
4 answers

Initialize your hash as follows:

> hash = Hash.new{|hash,key| hash[key] = "No element against #{key}"}
 => {}
> hash['a']
 => "No element against a" 
> hash['a'] = 123
 => 123 
> hash['a'] 
 => 123 
> hash['b'] = nil
 => nil 
> hash['b']
 => nil 

Hope this helps :)

-2
source
irb(main):001:0> h = Hash.new('No element present')
=> {}
irb(main):002:0> h[1]
=> "No element present"
irb(main):003:0> h[1] = nil
=> nil
irb(main):004:0> h[1]
=> nil
irb(main):005:0> h[2]
=> "No element present"
+3
source

you can use the method instead has_key?

val = h.has_key?('key') ? h['key'] : "No element present"
+2
source
val = h.has_key?("key") ? h['key'] : "No element present"
0
source

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


All Articles