Forum: Ruby value returned from code block

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
0ed1fc95a73b8626b25b6806ed7497f1?d=identicon&s=25 Spitfire (Guest)
on 2006-12-25 18:11
(Received via mailing list)
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?
Ec5a599777854c540fd102ef4691fe10?d=identicon&s=25 Rimantas Liubertas (Guest)
on 2006-12-25 18:26
(Received via mailing list)
>    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
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2006-12-25 18:26
(Received via mailing list)
On 25.12.2006 18:08, Spitfire wrote:
>
>     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
Ec5a599777854c540fd102ef4691fe10?d=identicon&s=25 Rimantas Liubertas (Guest)
on 2006-12-25 18:44
(Received via mailing list)
> >    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
This topic is locked and can not be replied to.