"downto" the nitty-gritty

Z

zetetic

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...
 
M

Matthias Luedtke

zetetic said:
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
 
R

Robert Klemme

zetetic said:
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):
x
=> 1=> 1

Kind regards

robert
 
Z

zetetic

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:

so IRB suppresses the return value output.

Signed,

Ruby Newbie
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top