C?dric Foll wrote:

>Hi,
>
>why the '+' method of nil isn't defined ?
>
>For exemple:
>    nil + "aaa" should return "aaa"
>    nil + 3 should return 3
>    nil + [1,2] should return [1,2] ....
>Perl works like that (at least for the first two exemple).
>It is convenient to do something like
>while gets do
> res += $_
>end
>
>without having to do res = "" before.
>
>Regards.
>
>--
>Cedric Foll
>courriel: cedric dot foll at laposte dot net
>
>
>
>
The problem here is that nil + "aaa" doesn't work the same way as in 
Perl, Ruby is an OO language and does things differently.

Here's what happens.
1) 'nil' is an object of the type NilClass.
2) The '+' is taken to be a method call on 'nil' with arguments of "aaa".
3) 'nil' has no such method '+'
4) 'nil' raises an exception over missing method '+'

Something similar happens with fred + "aaa" except here 'fred' is a 
reference to an object that at this point references no object, it 
therefore has no methods and doesn't know how to do '+'. So it too 
raises an exception.

When you do fred = "" first you make 'fred' a reference to a String 
object which does have a '+' method and so fred + "aaa" works.

fred + "aaa" might look the same as $fred + "aaa" but the mechanics of 
the two languages are very much different.