Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through a range

I need to iterate from 1 up to a given number A. I have achieved this using the following code:

(1..A).step(1) do |n| puts n end

Is there any better method than this?

My default step will be 1.

like image 240
Jagdsh L K Avatar asked Sep 20 '25 20:09

Jagdsh L K


1 Answers

In this case more idiomatic [arguably] way would be to use Integer#upto:

1.upto(A) { |n| puts n }

Also, step(1) is a default one and you might simply iterate the range itself:

(1..A).each { |n| puts n }

Or, even using Integer#times:

A.times { |n| puts n + 1 }

Note, that Integer#times starts counting from 0 hence + 1 is required.

NB please also note the very valuable comment by @Stefan below.

like image 158
Aleksei Matiushkin Avatar answered Sep 23 '25 01:09

Aleksei Matiushkin