[英]Iterate through an array and list all but one item
我有一個要列出的項目數組,但是我想排除一個特定的項目,稱為“提示”。 我在考慮類似“除非item.name =='tip'”之類的內容,但不確定在哪里放置類似內容
<ul>
<% @order.each do |item| %>
<li><h2><%= item["quantity"] %> × <%= item["name"] %></h2></li>
<% end %>
</ul>
放置, unless .. end
<% .. %>
unless .. end
:
<ul>
<% @order.each do |item|
unless item['name'] == 'tip' %>
<li><h2><%= item["quantity"] %> × <%= item["name"] %></h2></li>
<% end
end %>
</ul>
示例(為簡潔起見,使用item['name']
代替item.name
):
require 'erb'
class Listing
def build
@order = [
{'quantity' => 1, 'name' => 'a'},
{'quantity' => 2, 'name' => 'tip'},
{'quantity' => 3, 'name' => 'c'},
]
template = ERB.new <<-TMPL
<ul>
<% @order.each do |item|
unless item['name'] == 'tip'%>
<li><h2><%= item["quantity"] %> × <%= item["name"] %></h2></li>
<% end
end %>
</ul>
TMPL
template.result binding
end
end
puts Listing.new.build
輸出:
<ul>
<li><h2>1 × a</h2></li>
<li><h2>3 × c</h2></li>
</ul>
有很多實現目標的可能性。 我建議使用next
關鍵字,因為它使您能夠忘記后面的代碼中的情況,而且它不需要封閉的end
關鍵字(當在這種情況下您有更多的代碼行時,很快就很難看一眼了。 unless … end
子句開始/結束, unless … end
:
<ul>
<% @order.each do |item|
next if item["name"] == 'tip' %>
<li><h2><%= item["quantity"] %> × <%= item["name"] %></h2></li>
<% end %>
</ul>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.