在我看来,我试图显示一个对象表,这是我的代码:
<div id='categories_show'>
<table border="1">
<tr>
<th>Categories</th>
<th>CBB's</th>
</tr>
<% for category in @critical_process.categories %>
<tr>
<td rowspan="<%= category.capability_building_blocks.size %>"><%= category.category_title %></td>
<td><%= category.capability_building_blocks.first.cbb_title %></td>
</tr>
<% (category.capability_building_blocks - category.capability_building_blocks.first).each do |cbb| %>
<tr>
<td><%= cbb.cbb_title %></td>
</tr>
<% end %>
<% end %>
</table>
</div>
但是这会引发错误:can't convert CapabilityBuildingBlock into Array
关系是正确的,错误来自我尝试减去数组的第一个对象的行:<% (category.capability_building_blocks - category.capability_building_blocks.first).each do |cbb| %>
有什么办法可以在数组中循环忽略数组中的第一个对象?
谢谢
答案 0 :(得分:12)
尝试使用Array.drop - http://www.ruby-doc.org/core/classes/Array.html#M000294
<% category.capability_building_blocks.drop(1).each do |cbb| %>
<tr>
<td><%= cbb.cbb_title %></td>
</tr>
<% end %>
答案 1 :(得分:4)
此外,这更具可读性(而且我80%确定它有效):
<%= category.capability_building_blocks[1..-1].each do |cbb| %>
您可以使用内置切片运算符从数组中选择所需的任何元素。 -1
表示数组中的最后一个元素。
答案 2 :(得分:3)
<%= (category.capability_building_blocks - [category.capability_building_blocks.first]).each do |cbb| %>
同时... 强>
stop_here = category.capability_building_blocks.length
category.capability_building_blocks[1..(stop_here)].each do |cbb|