3.7 Mixing Data Types

Ruby will always try to remain in the same data type as its operands. For example, if the integers 2 and 3 are added in Ruby, the result will also be an integer.

irb(main):001:0> 2 + 3
=> 5

Likewise, when adding two floats, the result will also be a float.

irb(main):002:0> 2.0 + 3.0
=> 5.0

When Ruby encounters two operands of different data types, it will convert them to match where possible.

irb(main):003:0> 2 + 3.0
=> 5.0

The issue of dividing integers like 5 / 2 can finally be resolved. We are able to force Ruby to convert integer expressions into float expressions. Simply throw a float into the mix.

irb(main):004:0> 1.0 * 5 / 2
=> 2.5

Of course, it is sometimes impossible to convert the data types to match. In this case, Ruby will output a TypeError.

irb(main):005:0> x = 1 + "hello"
TypeError: String can't be coerced into Fixnum
     from (irb):4:in '+'
     from (irb):4

Get Computer Science Programming Basics in Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.