"downto" the nitty-gritty

1.downto(1) {|i| puts i}
=> 1

1.downto(2) {|i| puts i}
=> 1

Is this right? The block is always executed once, even when the limits
would suggest otherwise? 1.upto(0) does the same thing...

zetetic wrote:

1.downto(1) {|i| puts i}
=> 1

1.downto(2) {|i| puts i}
=> 1

Is this right? The block is always executed once, even when the limits
would suggest otherwise? 1.upto(0) does the same thing...

Hello zetetic,
as far as I can see the block is actually never _executed_ when you say

1.downto(2) {|i| puts i}

the expression just _evaluates_to_ 1 because you obviously called a method on 1. Look at the output, it says

irb(main):007:0> 1.downto(2) {|i| puts i}
=> 1

and doesn't execute the block. Now consider

irb(main):009:0> 1.upto(5) {|i| puts i}
1
2
3
4
5
=> 1

how it _executes_ the block and also _returns_ 1 at the end.

Regards,
Matthias

1.downto(1) {|i| puts i}
=> 1

1.downto(2) {|i| puts i}
=> 1

Is this right? The block is always executed once, even when the
limits would suggest otherwise? 1.upto(0) does the same thing...

That's not true. You probably mixed output in IRB as #upto and #downto return self (i.e. 1 in your case):

1.downto(1) {|i| puts "x"}

x
=> 1

1.downto(2) {|i| puts "x"}

=> 1

1.upto(0) {|i| puts "x"}

=> 1

Kind regards

    robert

ยทยทยท

zetetic <tomascabeza@gmail.com> wrote:

Thanks, that clears it up. I was about to post the very same code you
did once realizing I'd confused the IRB response with the output of the
block, due to my unfortunate choice of an example!

I guess another way to see it is:

conf.echo = false

so IRB suppresses the return value output.

Signed,

Ruby Newbie