Reputation: 65123
What is an easy way to generate an array that has values with a fixed distance between them?
For example:
1, 4, 7, 10,... etc
I need to be able to set start, end, and step distance.
Upvotes: 8
Views: 3078
Reputation: 303205
In Ruby 1.9:
1.step(12).to_a #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
1.step(12,3).to_a #=> [1, 4, 7, 10]
Or you can splat instead of to_a
:
a = *1.step(12,3) #=> [1, 4, 7, 10]
Upvotes: 4
Reputation: 838126
Try using Range.step
:
> (1..19).step(3).to_a
=> [1, 4, 7, 10, 13, 16, 19]
Upvotes: 20