Ruby 是强类型语言。因此它执行type conversion
而不是type casting
。现在有两种类型的转换 -implicit
和explicit
.
ruby 根据什么规则确定在什么上下文中应用哪种转换?
Ruby 是强类型语言。因此它执行type conversion
而不是type casting
。现在有两种类型的转换 -implicit
和explicit
.
ruby 根据什么规则确定在什么上下文中应用哪种转换?
Ruby is "duck typed", neither strong or weak typed, which means the behavior of a variable/object does not necessarily depend on the class it belongs to, but rather very "blind" and do method call at runtime without type check. If it cannot do that, it raises error.
Ruby does implicit conversion for Integer, String and some other internal classes. Whether to perform a conversion depends on the left operand. For example,
1 + "2"
The left operand is an integer, so ruby tries to do a math operation +. But the right operand is a string, so ruby will try to do a conversion (coersion) from string to integer. (Although it still failed. To make it work, one need to redefine the method + for Integer or we call monkey patch to do an explicit conversion using String#to_i)