← Back to Ruby Course | Chapter 2: Variables & Types | Lesson 7 of 7

Type Conversion

In this page:

  1. Type Conversion

Type Conversion

Ruby provides to_i, to_f, to_s, and to_a methods on many types for converting between them. to_i on a non-numeric string returns 0 rather than raising an error, which can hide input mistakes if you're not careful. Integer() and Float() (capitalized, used as functions) are stricter alternatives that raise an error on invalid input.

Warning: "abc".to_i returns 0 silently instead of raising an error -- use Integer("abc") if you want invalid input to raise instead.

Example: Type Conversion

markup
text = "42"
converted = text.to_i

puts converted.class
puts converted + 8

puts "abc".to_i    # silently becomes 0

begin
  Integer("abc")
rescue ArgumentError => e
  puts "Integer() raised: #{e.message}"
end
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.