Ruby Type Conversion

In programming, type conversion is the process of converting data of one type to another. For example, converting string data to numbers.

There are two types of conversion in Ruby:

  • Implicit Conversion - Automatic type conversion
  • Explicit Conversion - Manual type conversion

Ruby Implicit Conversion

In Ruby, implicit type conversion happens only in very limited cases, specifically when mixing integers and floats in arithmetic operations. For example,

integer_number = 123
float_number = 1.23

# Add integer and float
new_number = integer_number + float_number

# Display new value
puts "Sum: #{new_number}"
puts "Data Type: #{new_number.class}"

Output

Sum: 124.23
Data Type: Float

In this example, Ruby automatically converts the integer 123 to float (123.0) during the addition.

The resulting sum is 124.23, which is of Float type.

Note: The .class method returns the data type of an object in Ruby.


Ruby Explicit Type Conversion

In explicit type conversion, you manually convert an object from one data type to another using built-in methods.

Some common methods for explicit type conversion in Ruby are:

Method Description Example Result
.to_i Converts a value to an integer. "3.9".to_i 3
.to_f Converts a value to a float. 5.to_f 5.0
.to_s Converts a value to a string. 123.to_s "123"
.to_a Converts a range or enumerable to an array. (1..3).to_a [1, 2, 3]

Note: .to_a only works on ranges or objects that define it.


Example 1: String to Integer Conversion

value = "42"

# Convert string to integer
number = value.to_i

puts "Value: #{number}"
puts "Data Type: #{number.class}" 

Output

Value: 42
Data Type: Integer

Example 2: Integer to Float Conversion

value = 10

# Convert integer to float
float_number = value.to_f

puts "Value: #{float_number}"
puts "Data Type: #{float_number.class}"

Output

Value: 10.0
Data Type: Float

Example 3: Float to String Conversion

value = 3.14

# Convert float to string
string_value = value.to_s

puts "Value: #{string_value}"
puts "Data Type: #{string_value.class}"

Output:

Value: 3.14
Data Type: String

Data Loss During Conversion

In Ruby, data loss can occur when explicitly converting from one data type to another, especially from a more complex type to a simpler one. For example,

# Create a float value
value = 4150.12
puts "Float Value: #{value}"

# Convert float to integer
number = value.to_i
puts "Integer Value: #{number}"

Output:

Float Value: 4150.12  
Integer Value: 4150

Here, the decimal part .12 is lost during the conversion because .to_i drops everything after the decimal point.

Possible Data Loss During Ruby Type Conversion
Possible Data Loss During Ruby Type Conversion

For instance, suppose we convert a Float data to Integer and String. From the image above, we can see that:

  • Data loss occurs when Float is converted to Integer (the decimal part is removed).
  • No data loss occurs when Float is converted to String (the value is preserved as text).

More on Ruby Type Conversion

Rules for Type Conversion in Ruby

Understanding the rules for type conversion is crucial for avoiding unexpected results in your Ruby code. Here are some key points:

  1. Ruby performs implicit conversion only in limited numeric operations.
  2. Incompatible types like String and Integer are not implicitly converted.
  3. Explicit conversion must be done using methods like .to_i, .to_f, .to_s, etc.
  4. Invalid string-to-number conversions result in 0 (for .to_i) or 0.0 (for .to_f).
  5. Mixing different types without conversion raises a TypeError.
Invalid Conversion of Types in Ruby

Sometimes, converting between types doesn't work as expected. For example,

puts "abc".to_i   # 0
puts "abc".to_f   # 0.0

This happens because there is no numerical equivalent to the string "abc".

Converting Mixed Strings to Numbers

If a string starts with non-numeric characters, .to_i returns 0. If it starts with numbers, Ruby converts only the numeric part at the beginning:

puts "abc".to_i     # 0
puts "123abc".to_i  # 123
Mixing Data Types in Ruby

If you try to mix different types without converting them, Ruby will give an error:

# This causes an error
puts 10 + "5"  
 

To avoid this, always convert the string to a number first:

puts 10 + "5".to_i   # 15
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges