Cod*_*joy 23 ruby iterator ruby-on-rails-3
我在rails应用程序中的视图上使用ruby迭代器,如下所示:
<% (1..@document.data.length).each_with_index do |element, index| %>
...
<% end %>
Run Code Online (Sandbox Code Playgroud)
我认为增加了1 ..而不只是说:
@document.data
会得到上面的索引从1开始的技巧.但是,唉,上面的代码索引仍然是0到data.length(-1有效).所以我做错了什么,我需要索引等于1-data.length ...没有线索如何设置迭代器来做到这一点.
Tyl*_*ick 90
除非你使用像1.8这样的旧版Ruby(我认为这是在1.9中添加但我不确定),你可以each.with_index(1)用来获得一个基于1的枚举器:
在你的情况下,它将是这样的:
<% @document.data.length.each.with_index(1) do |element, index| %>
...
<% end %>
Run Code Online (Sandbox Code Playgroud)
希望有所帮助!
Mat*_*udy 29
我想也许你误解了each_with_index.
each 将迭代数组中的元素
[:a, :b, :c].each do |object|
puts object
end
Run Code Online (Sandbox Code Playgroud)
哪个输出;
:a
:b
:c
Run Code Online (Sandbox Code Playgroud)
each_with_index 迭代元素,并传入索引(从零开始)
[:a, :b, :c].each_with_index do |object, index|
puts "#{object} at index #{index}"
end
Run Code Online (Sandbox Code Playgroud)
哪个输出
:a at index 0
:b at index 1
:c at index 2
Run Code Online (Sandbox Code Playgroud)
如果你想要1索引,那么只需添加1.
[:a, :b, :c].each_with_index do |object, index|
indexplusone = index + 1
puts "#{object} at index #{indexplusone}"
end
Run Code Online (Sandbox Code Playgroud)
哪个输出
:a at index 1
:b at index 2
:c at index 3
Run Code Online (Sandbox Code Playgroud)
如果你想迭代一个数组的子集,那么只需选择子集,然后迭代它
without_first_element = array[1..-1]
without_first_element.each do |object|
...
end
Run Code Online (Sandbox Code Playgroud)
wor*_*wut 10
这可能与所讨论的each_with_index方法不完全相同,但我认为结果可能接近 mod 中要求的某些内容......
%w(a b c).each.with_index(1) { |item, index| puts "#{index} - #{item}" }
# 1 - a
# 2 - b
# 3 - c
Run Code Online (Sandbox Code Playgroud)
有关更多信息https://ruby-doc.org/core-2.6.1/Enumerator.html#method-i-with_index
用途Integer#next:
[:a, :b, :c].each_with_index do |value, index|
puts "value: #{value} has index: #{index.next}"
end
Run Code Online (Sandbox Code Playgroud)
产生:
value: a has index: 1
value: b has index: 2
value: c has index: 3
Run Code Online (Sandbox Code Playgroud)