On Fri, Nov 12, 2010 at 1:54 PM, Josh C. [email protected]
wrote:
Strong and weak typing - Wikipedia
2 + ‘2’ => TypeError: String can’t be coerced into Fixnum
Is Ruby strongly typed?
2 + 2.0 # => 4.0
Here it has implicitly converted the integer 2 to a float, in order to be
able to add them.
Strongly typed because there is no implicit conversion.
You can even make your specific example pass, exactly as
written, by defining String#coerce:
Exactly: this is an explicit conversion of types. Implicit
conversion would be if Ruby would convert 2 to 2.0 before invoking a
“float + operator”. But in Ruby just method :+ is invoked on instance
2 which internally uses the coerce mechanism to (hopefully) get two
instance which can properly work out how to +.
See
http://blog.rubybestpractices.com/posts/rklemme/019-Complete_Numeric_Class.html
class String
def coerce(num)
return num.to_s , self
end
end2 + ‘2’ # => “22”
There seems to be some disagreement what exactly “strongly” and
“weakly” means here. This becomes apparent of you read the
complementary article on Strong and weak typing - Wikipedia in
Wikipedia.
Kind regards
robert