Friday, March 16, 2007

JavaScript and Ruby difference of '+'

JavaScript does not convert numeric values to strings. For example:

"37" - 7 // returns 30
"37" + 7 // returns 377

Ruby will raise error when execute this example:

irb(main):001:0> "37" - 7
NoMethodError: undefined method `-' for "37":String
from (irb):1
irb(main):002:0> "37" + 7
TypeError: can't convert Fixnum into String
from (irb):2:in `+'
from (irb):2
irb(main):003:0> "37".to_i - 7
=> 30
irb(main):004:0> "37" + 7.to_s
=> "377"
irb(main):005:0>

No comments :