Hi gurus,
(even if I read the ng/list for some month, I never saw this
questions, so i put it myself.
Anyway, those could be old question, tuby-talk is a huge list an
it’s easy to miss something, sorry…)
DISCLAIMER: the above is done with 1.6.8
( little testing with ruby-1.8.0-20021226 win32 seem to give the same
result )
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
It seems to me that “puts” works using .to_s on every object ,
String.+ is not ?
And… if ruby knows that 1 is Fixnum, anf that it should be translated
to a String… what way it tryes to do this ?
this actually is the same with everything!
irb(main):025:0> b=nil
=> nil
irb(main):026:0> a=“string”
=> "string"
irb(main):027:0> a+=b
TypeError: failed to convert nil into String
from (irb):27:in +' from (irb):27 irb(main):028:0> b=true => true irb(main):029:0> a+=b TypeError: failed to convert true into String from (irb):29:in
+'
from (irb):29
1.1
but…
(a=3, b=nil)
irb(main):035:0> a+=b
TypeError: nil can’t be coerced into Fixnum
from (irb):35:in `+'
from (irb):35
I still think 3+nil should simply be 3, but anyway, why we’ve got a
different result from those above?
What’s the difference beetween “convert” and “coerce”
(don’t think about real life difference please
(and, from “string+nil”, we go to “nil+string”)
(NilQuestion “nil+”)
why nil does’nt have a “+” method?
It seem reasonable (and useful) having nothing +something giving back
nothing.
Maybe that’s impossible in the same way Fixnum.++ is ?
(NilQuestion “puts”)
Why :
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?)
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?
(maybe that’s related to things like this :
irb(main):017:0> a=nil
=> nil
irb(main):018:0> b=a.to_s+“bla”
=> “bla”
and, well, I think that could make sense.
BTW, having NilClass.+ eliminates this difference )