On Fri, Feb 07, 2003 at 11:36:55PM +0900, gabriele renzi wrote:
> 1)
> 
> Why this don't work:
> 
> irb(main):001:0> a="strink"
> => "strink"
> irb(main):002:0> puts a+1
> TypeError: failed to convert Fixnum into String
>         from (irb):2:in `+'
>         from (irb):2
> 
> 
> 
> and this does:
> 
> irb(main):003:0> puts a+1.to_s
> strink1
> => nil

Same question asked recently, see thread starting at [ruby-talk:63340]

The answer generalises to nil.

> I still think 3+nil should simply be 3

You can override the '+' method on Fixnum if you want this to occur, but the
default Ruby behaviour is sensible. nil means either 'no object' or
'uninitialised variable', and usually trying to add one of these would be an
error. If you're sure that's what you want, use 'to_i'.

> It seem reasonable (and useful) having nothing +something giving back
> nothing.

Maybe, but 'nil' isn't really the same as "zero" or "an empty string"

> irb(main):012:0> puts nil
> nil
> => nil
> irb(main):013:0> puts nil.to_s
> 
> => nil
> 
> 
> It seems obvious that my previous assertion (puts using to_s) is wrong
> , or we are always checking that an obj is not null ?
> ( lot of cheking?) 

I think puts is calling the 'inspect' method there, but I'm not sure.

> Anyway, I understand that writing "nil" when a var is actually nil is
> good for debugging, but why to_s should not give the same?

Because it gives a way to get the behaviour you asked for earlier, if you
are explicit about it. e.g. if you want to concatenate a string with a
variable which might be nil, use to_s:

   a = "hello"
   b = nil
   c = a + b.to_s
   puts c            >> "hello"

In the same way, if you want to add a number which might not be a number,
use to_i:

   a = "53 bananas"
   b = nil
   c = a.to_i + b.to_i
   puts c           >> 53

Regards,

Brian.