Integer conversion turns text input into an integer so Ruby can use it in numeric expressions. Keyboard input from gets is text, so a calculation such as temperature conversion uses gets.to_i before arithmetic. section 1.1.7
Ruby provides several conversion behaviors:
- String#to_i performs a permissive conversion: "123hello" becomes 123, while "hello" becomes 0. section 7.4.3
- Integer performs a stricter conversion and raises an exception for invalid input such as "123hello". section 7.4.3
- Calling to_i on an integer returns that integer; converting an integer to a float with to_f is also acceptable. section 7.4.3
- Conversion creates or returns an object of the target class rather than typecasting the original object. section 7.4.3
Converting input for a temperature calculation
celsius = gets.to_i fahrenheit = (celsius * 9 / 5) + 32 puts fahrenheit With input 100, the program calculates and prints 212. The conversion can also be written inline as (gets.to_i * 9 / 5) + 32. section 1.1.7
>> "123abc".to_i
=> 123
>> Integer("123abc")
ArgumentError: invalid value for Integer(): "123abc"
>> Float("3")
=> 3.0
>> Float("-3")
=> -3.0
>> Float("-3xyz")
ArgumentError: invalid value for Float(): "-3xyz"
Compare permissive to_i behavior with strict Integer and Float conversions, including successful and failing inputs. section 7.4.3
