Declaring an integer Range with step != 1 in Ruby

后端 未结 3 1653
感情败类
感情败类 2020-12-17 15:09

UPDATE 2: For posterity, this is how I\'ve settled on doing it (thanks to Jorg\'s input):

100.step(2, -2) do |x|
    # my code
end
         


        
3条回答
  •  执念已碎
    2020-12-17 15:22

    You can't declare a Range with a "step". Ranges don't have steps, they simply have a beginning and an end.

    You can certainly iterate over a Range in steps, for example like this:

    (2..100).step(2).reverse_each(&method(:p))
    

    But if all you want is to iterate, then what do you need the Range for in the first place? Why not just iterate?

    100.step(2, -2, &method(:p))
    

    This has the added benefit that unlike reverse_each it does not need to generate an intermediate array.

提交回复
热议问题