This one got me a bit also at first, but it's like others have said.
Maybe this will make it clearer:
class Array
# Build a string from this array, formatting each entry
# then joining them together.
def join( sep = $, format = "%s" )
collect do |item|
sprintf( format, item )
end.join( sep )<<<<big confusing stmt
end
end
This would create the endless loop that you expected. Notice that
instead of creating a subclass called ArrayMine that extends Array, I've
instead redefined the join method of the Array-class itself. Since
Array.collect returns an Array, Array.join would now cause an endless
recursive loop creating an infinitely long array.
The gotcha is basically that ArrayMine.collect returns an Array, and not
an ArrayMine.
Regards,
Helge Elvik
···
-----Original Message-----
From: Tom Rauchenwald [mailto:its.sec@gmx.net]
Sent: 27. juni 2006 15:46
To: ruby-talk ML
Subject: Re: newbie doesn't understand why's example
dave rose <bitdoger2@yahoo.com> writes:
in why's poignant guide to ruby...
class ArrayMine < Array
# Build a string from this array, formatting each entry
# then joining them together.
def join( sep = $, format = "%s" )
collect do |item|
sprintf( format, item )
end.join( sep )<<<<big confusing stmt
end
end
why doesn't this loop recursively forever? what's happening here at
the
big confusing stmt??? please explain....tia
collect returns an Array, as has been said.
Maybe it is clearer if you use a Variable:
foo= collect do |item|
sprintf( format, item )
end
foo.join(sep)