about ruby range?

后端 未结 3 1760
抹茶落季
抹茶落季 2020-12-20 11:50

like this

range = (0..10)

how can I get number like this:

0 5 10 

plus five every time but less than 10

3条回答
  •  感情败类
    2020-12-20 12:18

    The step method described in http://ruby-doc.org/core/classes/Range.html should do the job but seriously harms may harm the readability.

    Just consider:

    (0..20).step(5){|n| print ' first ', n }.each{|n| print ' second ',n }
    

    You may think that step(5) kind of produces a new Range, like why_'s question initially intended. But the each is called on the (0..20) and has to be replaced by another step(5) if you want to "reuse" the 0-5-10-15-20 range.

    Maybe you will be fine with something like (0..3).map{|i| i*5}?

    But "persisting" the step method's results with .to_a should also work fine.

提交回复
热议问题