试图将数组分成三个不均匀的数组(Ruby on Rails)

时间:2013-09-21 19:04:00

标签: ruby arrays

这是将产生13个页面标题的数组(我相信它是一个数组)的代码。对于下拉菜单,我希望将0-5标题放在自己的div中,将6-8放在第二个div中,将9-12放在第三个div中。我在这里找不到这个确切的问题/答案。

<% @cms_site.pages.root.children.published.each. do |page| %>
  <%= link_to page.label, page.full_path %>
<% end %>

谢谢!

2 个答案:

答案 0 :(得分:1)

你有什么尝试? #each对于这种情况不是很好用。您可能希望将其分成3个不同的循环,如下所示:

<% @cms_site.pages.root.children.published[0,5].each do |page| %>
  <%= link_to page.label, page.full_path %>
<% end %>

<% @cms_site.pages.root.children.published[6,8].each do |page| %>
  <%= link_to page.label, page.full_path %>
<% end %>

<% @cms_site.pages.root.children.published[9,12].each do |page| %>
  <%= link_to page.label, page.full_path %>
<% end %>

修改 看起来你有一些逻辑问题,至少你首先尝试它是明智的。

那里的代码应该可以工作,但它不是真的DRY,它可以被提取到一个帮助器方法,它使用迭代器的章节或者可能使用不同的迭代器(例如each_with_index)并处理检查块中的每个索引。做你要求的事情还有很多方法。

答案 1 :(得分:1)

基本上,如果你正在处理一个数组,并且你想每次从中获取完全相同的元素,这里是如何切片:

# Your Array
elements = [1,2,3,4,5,6,7,8,9,10,11,12]

# This will give you three arrays inside one array. The first will be first six
# elements starting from 0, the second is 3 elements starting from 6, etc.
arrays = [ elements[0,6], elements[6,3], elements[9,3] ]

现在,您可以遍历数组并重用代码来生成所需的代码。

arrays.each do |ar|
  # Now render for each array as you please, and reuse the same code.
end