Reputation: 49
I'm trying to return the first element in the given array that matches an element in a preset array. I have this:
def find_the_cheese(a)
cheese_types = ["cheddar", "gouda", "camembert"]
a.collect{|c| cheese_types.include?(c)}.include?(true)
end
But it returns true
rather than the c
value from the enclosed brackets. How can I return the matching element?
Upvotes: 1
Views: 236
Reputation: 322
Following code will returning elements from food which include in cheese_types
def find_the_cheese(food)
cheese_types = ["cheddar", "gouda", "camembert"]
food & cheese_types
end
Upvotes: 2
Reputation: 168081
CheeseTypes = ["cheddar", "gouda", "camembert"]
def find_the_cheese(a)
(a & CheeseTypes).first
end
Upvotes: 0
Reputation: 36101
The Array class includes the Enumerable module. Enumerable#find does just that:
def find_the_cheese(foods)
cheeses = ["cheddar", "gouda", "camembert"]
foods.find { |food| cheeses.include?(food) }
end
Upvotes: 1