在 Ruby 中创建具有开始值、结束值和浮点值步长的数组

Create array in Ruby with begin value, end value and step for float values

如何创建一个数组,其中包含一个范围内的值(具有开始值和结束值)和一个步骤?它应该支持 float 类型的开始和结束值。

对于 具有自定义步进的浮动,您可以像这样使用 Numeric#step

-1.25.step(by: 0.5, to: 1.25).to_a
# => [-1.25, -0.75, -0.25, 0.25, 0.75, 1.25] 

如果您正在研究如何只使用 整数值,请参阅 this post or that post 了解如何创建范围并简单地调用 .to_a结尾。示例:

(-1..1).step(0.5).to_a
# => [-1.0, -0.5, 0.0, 0.5, 1.0]