liveBook · Manning

Integer conversion

As explained in The Well-Grounded Rubyist, Fourth Edition

Integer conversion transforms input data into an integer value suitable for numeric computation.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains permissive and strict conversions, edge cases, object results, and the distinction from typecasting.
Examples
Uses interactive and file-based temperature converters, plus contrasting inputs such as "123abc" and "hello".
What it assumes
Assumes basic Ruby expressions and introduces input conversion through gets before extending the pattern to files.
What you can do after
Apply it via Ruby's to_i and Integer methods when preparing input for integer arithmetic.
How it connects
Connects integer conversion with string conversion, floating-point conversion, keyboard input, file I/O, exceptions, and typecasting.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.