← Back to the PhRUG strings demo

What is implicit conversion?

Implicit conversion happens when an operation converts a value to a type it can use. The operation chooses whether to convert the value and which type to use. Ruby 4.0 implicit conversion guide

When Ruby converts a number

p(7 / 2)    # 3
p(7 / 2.0)  # 3.5

With two integers, / gives an integer result. In 7 / 2.0, Ruby uses a floating-point value for 7 in the division. Ruby 4.0 integer division

When you need to convert a value

p("2" + "3")  # "23"
p("2" + 3)    # raises TypeError

With a string on the left, + joins text. It accepts a string or an object whose to_str method returns a string. The integer 3 lacks to_str, so Ruby raises TypeError. Ruby 4.0 String#+, string-convertible objects

Call to_s on the number to join text. Call Integer on the text to add numbers. Ruby 4.0 Integer#to_s, Kernel#Integer

p("2" + 3.to_s)     # "23"
p(Integer("2") + 3) # 5