[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

value returned from code block

Spitfire

12/25/2006 5:09:00 PM

I've read that in Ruby the value returned from a code block is the
value of the last expression executed. Is it so? If Yes, I don't
understand the value returned by the following code block!

def clistIter
clist = [1, 2, 3]
clist.each do |elem|
yield(elem)
end
end

clistIter { |e| print e }

## output in irb:
## 123 => [1, 2, 3]
##
## returned value:
## => [1, 2, 3]

Can someone explain how come an array is returned as result?

--
_ _ _]{5pitph!r3}[_ _ _
__________________________________________________
?I'm smart enough to know that I'm dumb.?
- Richard P Feynman
3 Answers

Robert Klemme

12/25/2006 5:21:00 PM

0

On 25.12.2006 18:08, Spitfire wrote:
> I've read that in Ruby the value returned from a code block is the
> value of the last expression executed. Is it so? If Yes, I don't
> understand the value returned by the following code block!
>
> def clistIter
> clist = [1, 2, 3]
> clist.each do |elem|
> yield(elem)
> end
> end
>
> clistIter { |e| print e }
>
> ## output in irb:
> ## 123 => [1, 2, 3]
> ##
> ## returned value:
> ## => [1, 2, 3]
>
> Can someone explain how come an array is returned as result?

Because #each ignores all return values from the block (it is invoked
once per element visited) and chooses to return self. This is how it
could look like internally (it's coded in C of course):

>> class Array
>> def demo_each
>> for i in 0...length
>> yield self[i]
>> end
>> self
>> end
>> end
=> nil
>> [1,2,3].demo_each {|e| p e; 666}
1
2
3
=> [1, 2, 3]

Kind regards

robert

Rimantas Liubertas

12/25/2006 5:25:00 PM

0

> I've read that in Ruby the value returned from a code block is the
> value of the last expression executed. Is it so? If Yes, I don't
> understand the value returned by the following code block!
<...>
> ## returned value:
> ## => [1, 2, 3]
>
> Can someone explain how come an array is returned as result?

In ruby 1.8 assignment always returns rvalue.


Regards,
Rimantas
--
http://rim...

Rimantas Liubertas

12/25/2006 5:43:00 PM

0

> > Can someone explain how come an array is returned as result?
>
> In ruby 1.8 assignment always returns rvalue.

I should have read more carefully. What I said is true, but has
nothing to do with
your case, sorry for the noise.

Regards,
Rimantas
--
http://rim...