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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With