user572273
user572273

Reputation:

Custom message where key is not present in a hash

By definition ruby hashes return nil when a key is not present. But I need to use a custom message in the place of nil. So I'm using something like this:

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

But this has a serious drawback. If there's a assigned nil against the key this will return "No element present" in that case also.

Is there a way to achieve this flawlessly?

Thanks

Upvotes: 3

Views: 228

Answers (4)

Sarwar Erfan
Sarwar Erfan

Reputation: 18068

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

Upvotes: 0

intellidiot
intellidiot

Reputation: 11228

Initialize your hash this way:

> 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 :)

Upvotes: -2

Tarscher
Tarscher

Reputation: 1933

you can use the has_key? method instead

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

Upvotes: 2

DNNX
DNNX

Reputation: 6255

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"

Upvotes: 3

Related Questions