生成一个值之间有固定距离的数组的简单方法是什么?
例如:
1, 4, 7, 10,... etc
我需要能够设置开始、结束和步长距离。
发布于 2011-01-30 01:44:32
尝试使用Range.step
> (1..19).step(3).to_a
=> [1, 4, 7, 10, 13, 16, 19]
发布于 2011-01-30 02:46:20
在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]
或者你可以用splat代替to_a
a = *1.step(12,3) #=> [1, 4, 7, 10]
https://stackoverflow.com/questions/4838381
复制相似问题