0

I am trying to do a comparison and return a statement whether the item is inside of the array or not. Menu is an object that I have in active record which is composed of 3 attributes, the menu type, meal and the restaurant id. For the meal attribute I had a variable set to it which is actually an array that contains the names of meals.

In my code when I do puts"#{menu.meal}" I get back...

["Pancakes W/ Eggs and Bacon", "Bacon Egg and Cheese", "Oatmeal W/ Raisins", "Scrambled Eggs W/ Grits", "Blueberry Waffles W/ Syrup", "Chocolate Chip Pancakes W/ Sausage", "Yogurt Muffin"]

which is the array of meals that I have set in my seeds file. In the code below what I am trying to do is when the user enters the meal that it wants I want to search through all the meals if it exits, and if it does then the user can proceed and if not I want to output an error message saying that it does not exist.

 puts "What meal would you like to order"
 item_meal = gets.chomp


 menus_meals = res.menus.select do |menu|
   binding.pry
   menu.meal == item_meal
1
  • Please see "How to Ask" and the linked pages and "mcve". When asking about code we need the minimal code necessary to demonstrate the problem. As is your code won't run so we can't test it. Commented Oct 24, 2019 at 22:17

1 Answer 1

1

It seems your code is correct, I would just advise that you use include? in this case as you are only trying to check if item_meal is present in menus.

if res.menus.include?(item_meal)
  # user proceeds
else
  # show an error message
end
Sign up to request clarification or add additional context in comments.

1 Comment

Depending on length of array and where the item you're searching for may be, .find can be orders of magnitude faster than .include?. See this gist as an example.

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.