Ruby integer enumerator with offset
質問
Is there a better/cleaner way to create a Ruby enumerator (i.e. for a for loop) that begins with an offset? A way that only involves the number of times and the offset once.
For example, iterate 10 times starting at 100:
> 100.upto(100 + 10)
#<Enumerator: 100:upto(110)>
Or
> 10.times.collect{|i| 100 + i}.each
#<Enumerator: [100, 101, 102, 103, 104, 105, 106, 107, 108, 109]:each>
Something like this would be nice:
100.next(10)
解決
Maybe this could work:
(1..10).each.with_index(100) do |elem, i| puts "#{i}: #{elem}" end
100: 1
101: 2
102: 3
103: 4
104: 5
105: 6
106: 7
107: 8
108: 9
109: 10
他のヒント
(100..110).each
or more generic
(start..start+offset).each
How about a range:
[6] pry(main)> offset = 10
=> 10
[7] pry(main)> (100..(100 + offset)).collect { |i| i }
=> [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110]
[8] pry(main)> (100..(100 + offset)).collect { |i| i }
所属していません StackOverflow