Reputation: 4306
I have a method which accepts a hash, and I have an array of keys (ordered by preference) which I want to check the hash for and return the value of the first matching key that's found which is not blank?
. So far I have the following, but since I utilize this method heavily, I'm wondering if there is a more efficient way of going about it?
result = [:title, :name, :identifier, :slug].each do |key|
if my_hash[key].present?
return my_hash[key]
break
end
end
So given the following hash:
{
id: 10,
title: "",
name: "Foo",
slug: "foo"
}
I would expect result
to be: "Foo"
Upvotes: 1
Views: 184
Reputation: 54882
You can do the following:
whitelisted_keys = [:title, :name, :identifier, :slug]
filtered_hash = your_hash.slice(*whitelisted_keys) # will only get pair matching your whitelisted_keys
# return all `.present?` key/values pairs:
filtered_hash.select{ |k,v| v.present? }
# return an array of the first key/value pair present:
filtered_hash.find{ |k,v| v.present? } # append .last to get the value
As Sawa pointed out in the comment, this is not the most efficient way but might be more "readable"
Upvotes: 0
Reputation: 168101
Your way is probably close to the best from the point of view of efficiency. But if you want it to be more elegant, retaining the efficiency, then:
my_hash[%i[title name identifier slug].find{|key| my_hash[key].present?}]
Upvotes: 5