Build array from interval and duration

Is there a shorter way to build an array based on an interval and
duration than the way I attempted?

def build_array(step,duration)
counter = 0
a = []
while counter <= duration do
a << counter
counter += step
end
return a
end

irb(main):010:0> dt = 0.5
=> 0.5
irb(main):011:0> total_time = 10
=> 10
irb(main):012:0> time_steps = build_array(dt,total_time)
=> [0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5,
7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0]

Thank you!

Jason L. [email protected] writes:

Is there a shorter way to build an array based on an interval and
duration than the way I attempted?

Yep:
irb(main):004:0> 0.step(10, 0.5).to_a
=> [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0,
6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0]

Yep:
irb(main):004:0> 0.step(10, 0.5).to_a

That’s great. Thank you.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs