Type Conversion
In this page:
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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: