2013-01-17 46 views
11

我在Rails应用程序中使用Ruby的迭代器在视图上,像这样:each_with_index_do从1开始的索引

<% ([email protected]).each_with_index do |element, index| %> 
    ... 
<% end %> 

我想到了另外的1 ..而不是只说: @document.data

会得到上面的索引从1开始的技巧。但是,上面的代码索引仍然是0到data.length(-1有效)。所以我做错了什么,我需要索引等于1-data.length ...不知道如何设置迭代器来做到这一点。

+0

阵列的第一索引总是要'0'。 – Kyle

+0

该索引始终为零。为什么这有关系? –

+0

@Codejoy - 由于您的问题已被多个用户解答,因此您可以点赞/接受一些答案。 – Kyle

回答

19

我想也许你误解each_with_index

each将遍历元件以阵列

[:a, :b, :c].each do |object| 
    puts object 
end 

其输出;

:a 
:b 
:c 

each_with_index迭代的元件,并且也通过在索引(从零开始)

[:a, :b, :c].each_with_index do |object, index| 
    puts "#{object} at index #{index}" 
end 

其输出

:a at index 0 
:b at index 1 
:c at index 2 

如果希望则1索引只需添加1.

[:a, :b, :c].each_with_index do |object, index| 
    indexplusone = index + 1 
    puts "#{object} at index #{indexplusone}" 
end 

,输出

:a at index 1 
:b at index 2 
:c at index 3 

,如果你想遍历数组的一个子集,那么就选择子集,然后遍历它

without_first_element = array[1..-1] 

without_first_element.each do |object| 
    ... 
end 
+0

好吧,我意识到我的方式的错误。 – Codejoy

+0

不用担心@Codejoy –

2

有没有这样的事情索引从1开始。如果你想跳过阵列中的第一项使用next

<% ([email protected]).each_with_index do |element, index| %> 
    next if index == 0 
<% end %> 
+1

琐事:Perl有一个全局变量''['''您可以设置为使所有数组索引从1开始或其他任何值。我们应该非常高兴Ruby没有这个。 –

2

数组索引始终为零。

如果你想跳过第一个元素,它听起来像你这样做:

@document.data[1..-1].each do |data| 
    ... 
end 
1

如果我理解你的问题吧,你想从1开始索引,但在红宝石数组作为0基指标,所以最简单的方法将是

给出@document.data是一个数组

index = 1 
@document.data.each do |element| 
    #your code 
    index += 1 
end 

HTH

+0

有史以来最酷的事情,但它的工作感谢 – MZaragoza

42

除非你使用的是老式的Ruby像1.8(我认为这是在1中添加。9,但我不知道),你可以用each.with_index(1)获得基于1枚举:

在你的情况下,它会是这样:

<% @document.data.length.each.with_index(1) do |element, index| %> 
    ... 
<% end %> 

希望帮助!

+3

当然这些日子更好的答案。 –

0

我有同样的问题,并通过使用each_with_index方法解决它。但在代码中的索引中添加1。

@someobject.each_with_index do |e, index| 
    = index+1 
1

使用Integer#next

[:a, :b, :c].each_with_index do |value, index| 
    puts "value: #{value} has index: #{index.next}" 
end 

生产:

value: a has index: 1 
value: b has index: 2 
value: c has index: 3