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

Type Conversion

Type conversion changes one kind of value into another, like turning the text 5 into the number 5. Ruby has methods such as to_i and to_s for these changes.

In this page:

  1. Type Conversion
Syntax
ruby
"42".to_i
"3.14".to_f
42.to_s
(1..3).to_a

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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using "abc".to_i and expecting an error, when it silently returns 0; use Integer("abc") to raise ArgumentError.
  2. Adding a string and an integer such as "5" + 3, which raises TypeError until you convert one side.
  3. Using to_i on a decimal string such as "3.9" and expecting 4, when it gives 3.
Chapter Summary
  • Ruby has local, global, instance, and class variables.
  • Integer, float, boolean, nil, and symbol values are common types.
  • Type conversion changes a value from one type to another.
🔒

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.