[英]How do I get my current ruby program to loop through three input options and display if the same option has been used twice?
[英]how not to loop twice on the same items - RUBY
我有这个循环:
<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 class="fa-solid fa-check" style="color: green; margin-left: 10px"></i>
</p>
<% elsif ingredient.exclude? f.content%>
<p style="color: red">
<%=ingredient%>
<i class="fa-solid fa-xmark" style="color: red; margin-left: 10px"></i>
</p>
<%end%>
</li>
<% end %>
<%end%>
</ul>
<% end %>
在@fridge 变量上,我有 4 个值。 一旦我循环使用一种特定的成分,我就不想再循环使用它了。
您的代码中有一些对我来说不清楚的地方,但现在我无法提出问题,所以如果有问题,我希望您能纠正我。 为什么你有elseif
而不是只有else
?
如果要停止循环,只需在需要的地方使用break
词:
<% @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 class="fa-solid fa-check" style="color: green; margin-left: 10px"></i>
</p>
<% elsif ingredient.exclude? f.content%>
<p style="color: red">
<%=ingredient%>
<i class="fa-solid fa-xmark" style="color: red; margin-left: 10px"></i>
</p>
<%end%>
</li>
<% end %>
<%end%>
</ul>
<% end %>
并试图让你的代码更清晰:假设@fridge 是一个对象集合,而 item['ingredients'] 是一个字符串数组(所以成分是一个字符串),你可以尝试这样的事情:
<% @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 class="fa-solid fa-check" style="color: green; margin-left: 10px"></i>
</p>
<% else %>
<p style="color: red">
<%= ingredient %>
<i class="fa-solid fa-xmark" style="color: red; margin-left: 10px"></i>
</p>
<%end%>
</li>
<%end%>
</ul>
<% end %>
那是你的问题吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.