Jagdsh L K
Jagdsh L K

Reputation: 61

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.

Upvotes: 4

Views: 5914

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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.

Upvotes: 12

Related Questions