Type Conversion
Prerequisites: Getting user input
Type conversion means turning a value of one type into another — most often text from the user into a number.
Lenient conversion: to_i, to_f, to_s
p "42".to_i
p "3.5".to_f
p 42.to_s
p "42abc".to_i
p "abc".to_i
p 3.99.to_i
42
3.5
"42"
42
0
3
The to_* methods never fail. They read as much as they can and
give up quietly — "abc".to_i is 0, and 3.99.to_i cuts off the
decimal (it doesn't round). That's convenient but can hide bad input.
Strict conversion: Integer() and Float()
Integer(...) and Float(...) raise an error when the text isn't a
valid number:
p Integer("42")
p Float("3.5")
42
3.5
But Integer("abc") stops the program with an error:
invalid value for Integer(): "abc" (ArgumentError)
Use the strict versions for user input you want to validate; the
Basic Error Handling lesson shows how to catch the error and ask again.
Pass exception: false to get nil instead of an error:
p Integer("abc", exception: false)
nil
Common mistakes
- Trusting
to_ion user input: someone typesten, and your program silently treats it as0. - Expecting
to_ito round. Use3.99.roundfor rounding.
Practice
Convert "19.99" to a number, add 5, and print 24.99.
Show solution
price = Float("19.99")
puts price + 5
24.99