1

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?

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.