liveBook · Manning

Integer

As explained in The Well-Grounded Rubyist, Fourth Edition

Integer is Ruby's built-in class for representing whole-number values.

Integer is Ruby’s built-in class for representing whole-number values. Integers are objects: they have classes, receive messages, and belong to Ruby’s numeric class family beneath Numeric. section 8.3 section 8.3.1

Ruby integers support ordinary arithmetic and several representation rules:

  • Integer division returns an integer: 16 / 5 evaluates to 3; use a floating-point operand for floating-point division. section 8.3.2
  • Modulo returns a remainder, so 10 % 3 evaluates to 1. section 8.3.2
  • Prefixes select bases: 0x introduces hexadecimal, while a leading 0 introduces octal. section 8.3.2
  • Arithmetic operators are methods under Ruby’s operator syntax, as shown by 1.+(1) and 12./(3). section 8.3.2

Integer arithmetic in a temperature converter

A small Ruby program can keep its input and output as integers: celsius = 100; fahrenheit = (celsius * 9 / 5) + 32. The calculation demonstrates integer arithmetic inside a runnable program. section 1.1.5

Table 8.1 Common arithmetic expressions and their evaluative results

Expression

Result

Comments

1 + 1

2

Addition

10/5

2

Integer division

16/5

3

Integer division (no automatic floating-point conversion)

10/3.3

3.0303030303

Floating-point division

1.2 + 3.4

4.6

Floating-point addition

-12 - -7

–5

Subtraction

10 % 3

1

Modulo (remainder)

Compare integer division, floating-point division, subtraction, addition, and modulo through compact evaluated examples. section 8.3.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains object membership, arithmetic behavior, numeric bases, conversion, and operator methods through evaluated examples.
Examples
Uses arithmetic tables, hexadecimal and octal literals, base conversions, ASCII conversion, and a temperature converter.
What you can do after
Evaluate whole-number expressions, choose integer or floating-point division, and write simple integer-based Ruby programs.
How it connects
Connects Integer with Numeric, Float, scalar objects, strings, arithmetic operators, and object methods.

Also explained in

Compare how 15 books explain integer →

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.