Andre
Andre

Reputation: 11

How to return a string when there is an non-existent element in a hash using an array

I have this hash and this array, and execute the following command...

hash={"a"=>1,"b"=>2,"c"=>3,"d"=>4,"e"=>5,"f"=>6}
array=["b","a","c","f","z","q"]
print hash.values_at(*array).compact

So I want it to return something like:

#=> [2,1,3,6,"invalid","invalid"]

Is there a way to declare all other elements non-existent in the hash as "invalid", without declaring one by one (e.g. "g"=>"invalid", "h"=>"invalid"...)?

Upvotes: 1

Views: 315

Answers (3)

steenslag
steenslag

Reputation: 80085

If a hash has to respond with a default value for a nonexistent key, then this value has to be set. Usually it is set on the initialization of the hash:

hash = Hash.new("invalid")

but it can be done anytime

hash={"a"=>1,"b"=>2,"c"=>3,"d"=>4,"e"=>5,"f"=>6}
array=["b","a","c","f","z","q"]

hash.default = "invalid"
p hash.values_at(*array)  #compact is superfluous

# => [2, 1, 3, 6, "invalid", "invalid"]

Upvotes: 3

AnoE
AnoE

Reputation: 8345

Try this:

array.map { |key|
    hash.has_key?(key) ? hash[key] : 'invalid'
}

Upvotes: 2

max pleaner
max pleaner

Reputation: 26778

array.map do |key|
  hash.fetch key, 'invalid'
end

if fetch is called with one argument, then if the key doesn't exist it will raise an error. However an optional second argument can set a custom return value for nonexistent keys.

The benefit of this over hash.default= or passing the default in the Hash constructor is that the hash itself is not changed, so if you lookup a nonexistent key in the future it will return nil as expected instead of 'invalid'.

Upvotes: 3

Related Questions