liveBook · Manning

To_i

As explained in The Well-Grounded Rubyist, Fourth Edition

to_i is a Ruby conversion method that produces an integer representation of a value and can interpret a string in a specified numeric base.

Keyboard input arrives as a string. To use it in arithmetic, call `to_i`: `celsius = gets.to_i`. Ruby does not automatically turn a string of digits into a number; without conversion, multiplying the string repeats its contents rather than performing numeric multiplication. section 1.1.7 section 7.4.3

Listing 1.2 Interactive temperature converter (c2fi.rb)
print "Hello. Please enter a Celsius value: "
celsius = gets
fahrenheit = (celsius.to_i * 9 / 5) + 32
print "The Fahrenheit equivalent is "
print fahrenheit
puts "."

An interactive temperature converter shows `to_i` between reading a Celsius value and calculating its Fahrenheit equivalent. section 1.1.7

`to_i` is forgiving when called on a string: `"123abc".to_i` returns `123`, while `"hello".to_i` returns `0`. Calling it on an integer returns that integer. If accepting only a fully valid integer matters, `Integer("123abc")` raises an `ArgumentError` instead. section 7.4.3

Interpret digits in another base

Pass a base from 2 through 36 to interpret a string in that base: `"100".to_i(17)` returns `289`, and `"10".to_i(17)` returns `17`. For bases 8 and 16, strings also have the dedicated methods `oct` and `hex`. section 8.1.6 section 8.3.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains permissive string conversion, integer receivers, bases 2–36, and stricter alternatives without detailing implementation internals.
Examples
Uses temperature converters, `"123abc".to_i`, and base-conversion expressions such as `"100".to_i(17)`.
What it assumes
Builds on basic Ruby method calls and arithmetic while demonstrating conversion from keyboard input.
What you can do after
Apply it via Ruby's `to_i` to convert input for calculations or interpret strings in bases 2–36.
How it connects
Connects `to_i` to keyboard and file I/O, integer arithmetic, `to_f`, `Integer`, and numeric bases.

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.