ruby 对于索引,每个带索引的do从1开始

xmakbtuz  于 2022-12-26  发布在  Ruby
关注(0)|答案(8)|浏览(140)

我在一个rails应用的视图上使用了一个ruby迭代器,如下所示:

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

我想加上1...而不是仅仅说:第一个月
我会得到上面的索引从1开始的技巧。但是,唉,上面的代码索引仍然是0到data.length(实际上是-1)。所以我做错了什么,我需要索引等于1-data. length...不知道如何设置迭代器来做到这一点。

eqqqjvef

eqqqjvef1#

除非你使用的是像1.8这样的老Ruby(我想这是1.9中添加的,但我不确定),否则你可以使用each.with_index(1)来获得一个从1开始的枚举器:
在您的情况下,它将是这样的:

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

rkkpypqq2#

我想你可能误解了。
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
sy5wg1nm

sy5wg1nm3#

这可能不是完全相同的each_with_index方法的问题,但我认为结果可能接近的东西在国防部是问...

%w(a b c).each.with_index(1) { |item, index| puts "#{index} - #{item}" }

# 1 - a
# 2 - b
# 3 - c

For more information https://ruby-doc.org/core-2.6.1/Enumerator.html#method-i-with_index

yshpjwxd

yshpjwxd4#

使用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
toe95027

toe950275#

不存在从1开始索引这样的事情。如果您想跳过数组中的第一项,请使用next

<% (1..@document.data.length).each_with_index do |element, index| %>
  next if index == 0
<% end %>
5kgi1eie

5kgi1eie6#

数组索引总是从零开始的。
如果你想跳过第一个元素,听起来你是这么做的:

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

hc2pp10m7#

如果我没理解错你的问题,你想从1开始索引,但是在ruby数组中是从0开始的,所以最简单的方法是
给定@document.data是一个数组

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

高温加热

anhgbhbe

anhgbhbe8#

我遇到了同样的问题,使用each_with_index方法解决了这个问题,但是在代码中给索引加了1。

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

相关问题