【问题标题】:Ruby 1.8.7 each_with_index index offsetRuby 1.8.7 each_with_index 索引偏移量
【发布时间】:2012-06-04 16:00:51
【问题描述】:

在 ruby​​ 1.8.7 的集合上使用 each_with_index 时,如何指定从哪个索引开始?

collection.each_with_index do |element, index = 1|
  #do smth
end

这样使用会出现以下错误:

syntax error, unexpected '=', expecting '|'
collection.each_with_index do |element, i = 1|

【问题讨论】:

    标签: ruby-on-rails ruby ruby-enterprise-edition


    【解决方案1】:

    试试这个:

    collection[4..-1].each_with_index do |element, index|
      #do smth
    end
    

    这个例子将从第五个元素开始。

    【讨论】:

    • 嗯,这不是我所需要的。我需要索引以1 开头,index 在块中进一步使用。
    • 我理解正确吗?例如,您有数组 ['a', 'b','c','d']。你想从元素'b'开始吗?或者您想要第一个索引,例如 1 而不是 0?
    • 我猜作者只需要method_that_uses_index(index+1) :)
    • [1,2,3,4,5,6].drop(3).each_with_index {|e,i|p e;p i}是另一种选择。
    猜你喜欢
    • 2011-08-04
    • 2012-08-25
    • 1970-01-01
    • 2014-07-19
    • 2018-12-31
    • 2016-02-23
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    相关资源
    最近更新 更多