Bgeo25
Bgeo25

Reputation: 49

First array element that matches an element in another array

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

Answers (3)

Vishal Zambre
Vishal Zambre

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

sawa
sawa

Reputation: 168081

CheeseTypes = ["cheddar", "gouda", "camembert"]
def find_the_cheese(a)
  (a & CheeseTypes).first
end

Upvotes: 0

ndnenkov
ndnenkov

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

Related Questions