I have this loop :
<div>
<% @ingredientsOfRecipes.each do |item| %>
<ul>
<%= item["name"] %>
<%@fridge.each do |f|%>
<% item['ingredients'].each do |ingredient| %>
<li style="display: flex; flex-drirection: row; align-items: center">
<% if ingredient.include? f.content%>
<p style="color: green">
<%=ingredient%>
<i style="color: green; margin-left: 10px"></i>
</p>
<% elsif ingredient.exclude? f.content%>
<p style="color: red">
<%=ingredient%>
<i style="color: red; margin-left: 10px"></i>
</p>
<%end%>
</li>
<% end %>
<%end%>
</ul>
<% end %>
On the @fridge variables, I have 4 values. and once I loop on a particular ingredient, I don't want to loop on it anymore.
CodePudding user response:
Why don't you just use break
break unless ingredient !=
'my_ingredient'
CodePudding user response:
There are some things that are not clear for me in your code, but right now I can't do questions, so I hope you can correct me if something is not working. Why you have elseif
instead of only else
?
If you want to stop the loop, simple use the break
word wherever you need:
<% @ingredientsOfRecipes.each do |item| %>
<ul>
<%= item["name"] %>
<% @fridge.each do |f|%>
<% item['ingredients'].each do |ingredient| %>
<li style="display: flex; flex-drirection: row; align-items: center">
<% break if ingredient.include? 'my_ingredient_that_should break_the_loop'%>
<% if ingredient.include? f.content %>
<p style="color: green">
<%=ingredient%>
<i style="color: green; margin-left: 10px"></i>
</p>
<% elsif ingredient.exclude? f.content%>
<p style="color: red">
<%=ingredient%>
<i style="color: red; margin-left: 10px"></i>
</p>
<%end%>
</li>
<% end %>
<%end%>
</ul>
<% end %>
And trying to do your code more clear: supposing @fridge is a collection of objects and item['ingredients'] is an array of strings (so ingredient is a String) you can try something like this:
<% @ingredientsOfRecipes.each do |item| %>
<ul>
<%= item["name"] %>
<% item['ingredients'].each do |ingredient| %>
<li style="display: flex; flex-drirection: row; align-items: center">
<% break if ingredient.include? 'my_ingredient_that_should break_the_loop'%>
<% if @fridge.collect(&:content).any? {|c| ingredient.include? c } %>
<p style="color: green">
<%= ingredient %>
<i style="color: green; margin-left: 10px"></i>
</p>
<% else %>
<p style="color: red">
<%= ingredient %>
<i style="color: red; margin-left: 10px"></i>
</p>
<%end%>
</li>
<%end%>
</ul>
<% end %>
Is that your question?