Re: newbie doesn't understand why's example

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs