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:
Syntax
"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
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
Login to try C/C++/Java/PHP code in the editor
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
- Using
"abc".to_iand expecting an error, when it silently returns0; useInteger("abc")to raiseArgumentError. - Adding a string and an integer such as
"5" + 3, which raisesTypeErroruntil you convert one side. - Using
to_ion a decimal string such as"3.9"and expecting4, when it gives3.
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: