1

Ruby is strongly typed language. Thus it performs type conversion rather than type casting. Now there is two types of conversions - implicit and explicit.

Based on what rules ruby determines which kind of conversion to be applied on what context?

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
  • Forget the term ["strongly typed"](http://stackoverflow.com/a/9929697/395760). It's ill-defined, meaningless, worthless, arguably even harmful. –  Mar 09 '13 at 20:41
  • I think you have some concepts confused. *type conversion* and *type casting* are not alternatives. *type casting* is something that can happen in a statically typed language, but since Ruby is dynamically typed, that doesn't apply. – troelskn Mar 09 '13 at 20:42
  • @troelskn apologies. I have corrected my description. I put rather instead of rather than earlier. – Arup Rakshit Mar 09 '13 at 20:44

1 Answers1

2

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)

SwiftMango
  • 15,092
  • 13
  • 71
  • 136
  • left hand operand is an `integer`, thus ruby tried to do such implicit conversion using `to_int`.But string don't has `to_int` thus implicit conversion failed and an error comes to the screen as `TypeError: can't convert String into Integer`. Is my catch right? – Arup Rakshit Mar 09 '13 at 21:02
  • @Priti yes and no... Ruby uses type coersion (something between casting and coversion) for internal types, rather than directly calling "to_xxx" method. – SwiftMango Mar 09 '13 at 21:07