Integer
Integer() The Integer class represents whole numbers in Ruby. In modern Ruby (2.4+), Fixnum and Bignum are unified into just Integer, which automatically handles numbers of any size.
Creating Integers
# Direct literals
42 # => 42
-10 # => -10
0 # => 0
1_000_000 # => 1000000 (underscores allowed)
# Integer() conversion
Integer(3.14) # => 3 (truncates)
Integer("42") # => 42
Integer("100", 2) # => 4 (binary)
Once you have an integer value, Ruby gives you a full set of arithmetic operators that work the way you would expect from any modern language. Addition, subtraction, multiplication, and exponentiation all return new Integer objects without mutating the original. Division between two integers performs floor division by default, which is worth remembering when you are porting code from Python or JavaScript where the rules can differ. The modulo operator follows the sign of the divisor, so negative numbers behave consistently.
Integer Methods
# Basic math
42 + 1 # => 43
42 - 1 # => 41
42 * 2 # => 84
42 / 5 # => 8 (integer division)
42 % 5 # => 2 (modulo)
42 ** 2 # => 1764 (exponent)
# Predicates
42.even? # => true
42.odd? # => false
42.zero? # => false
0.zero? # => true
Beyond arithmetic, integers in Ruby double as bit vectors when you need to work with flags or low‑level data. The bitwise AND, OR, XOR, and NOT operators treat each integer as a binary sequence, which is especially useful for permission masks and compact state storage. Shifting left multiplies by powers of two, and shifting right divides, both without floating‑point overhead. Predicate methods like even? and zero? are small conveniences, but they keep conditional checks readable in loops and guards.
Bit Operations
# Binary operations
42 & 10 # => 2 (AND)
42 | 10 # => 50 (OR)
42 ^ 10 # => 48 (XOR)
~42 # => -43 (NOT)
# Shifting
42 << 1 # => 84 (left shift)
42 >> 1 # => 21 (right shift)
Once you have settled on an integer representation, you will often need to hand the value off to a different part of the program that expects a string, a float, or a rational number. Ruby makes these conversions straightforward with a small set of well‑named methods. The to_s method is particularly flexible because it accepts an optional base argument, letting you produce binary, octal, or hexadecimal strings without writing a custom formatter.
Integer to other types
# To float
42.to_f # => 42.0
# To string
42.to_s # => "42"
42.to_s(2) # => "101010" (binary)
42.to_s(16) # => "2a" (hex)
# To rational
42.to_r # => (42/1)
When you move from single values to sequences, integers become the natural driver for loops and ranges. Ruby leans hard into this idea with methods like times and step, which turn a number into something you can iterate over directly. The times method is essentially a zero‑based loop that runs the block exactly that many times, while step lets you control the increment. These helpers often replace C‑style for loops and make the code noticeably shorter.
Iteration
# Upward
5.times { |i| print i } # => 01234
# Range
(1..5).each { |i| print i } # => 12345
# Step
(0.step(10, 2)) { |i| print i } # => 0246810
The methods covered so far are building blocks. Putting them together is where integers show their real utility, whether you are solving a classic interview problem or formatting output for a report. The next two examples walk through a custom Roman numeral converter and the familiar FizzBuzz exercise. Both lean on integer arithmetic and iteration in ways that feel natural in Ruby once you have seen the patterns.
Practical Examples
Roman numerals (custom implementation)
def to_roman(num)
return "" if num == 0
roman_mapping.each do |value, letter|
return letter * (num / value) + to_roman(num % value) if num >= value
end
end
roman_mapping = [[1000, "M"], [900, "CM"], [500, "D"], [400, "CD"],
[100, "C"], [90, "XC"], [50, "L"], [40, "XL"],
[10, "X"], [9, "IX"], [5, "V"], [4, "IV"], [1, "I"]]
The Roman numeral converter above uses recursion and a mapping table to build the result string piece by piece. It is a clean example of how Ruby lets you express a divide‑and‑conquer approach without much ceremony. The same idea scales to other numeral systems, and the pattern of pairing values with symbols appears often in formatters and serializers. Next, FizzBuzz shows how integer divisibility checks combine with string building in a short loop.
FizzBuzz
(1..15).each do |i|
result = ""
result += "Fizz" if i % 3 == 0
result += "Buzz" if i % 5 == 0
puts result.empty? ? i : result
end
FizzBuzz is a small program, but it packs several Ruby idioms into a few lines: a range, an accumulator string, conditional appends with +=, and a ternary fallback. The same structure appears in any loop that needs to build output conditionally, from log formatters to report generators. When you step back from these examples, you will also notice that Ruby integers never overflow in the traditional sense, which leads into the next topic.
Bignum (Pre-Ruby 2.4)
# In older Ruby, integers > 2^62-1 were Bignum
# Now automatically handled by Integer
huge = 10**100 # Works fine, no overflow
puts huge.class # => Integer
Before Ruby 2.4, integers above a certain threshold were represented by a separate Bignum class, and Ruby would silently promote Fixnum values to Bignum as needed. That distinction is gone now, but the underlying behavior is the same: you can compute with arbitrarily large numbers and Ruby handles the memory and performance details for you. The Integer::MAX and Integer::MIN constants are available if you need to check platform limits, though they are rarely necessary in everyday code.
Constants
Integer::MAX # Largest integer
Integer::MIN # Smallest integer
Integers in Ruby are unlimited precision, making them perfect for mathematical calculations without overflow concerns.
Integer in real programs
Integers show up everywhere: counters, indexes, sizes, flags, and loop boundaries. That makes it worth knowing how Ruby handles division, conversion, and iteration helpers such as times or step. When you need a predictable whole number, integers are a better fit than floats because there is no rounding noise to chase later. They also work well with string conversion in different bases, which is handy when you are formatting output for logs, IDs, or simple binary and hexadecimal displays.
One more practical point is that integer code often reads best when the unit is obvious. If a value is a count of bytes, seconds, or items, naming it clearly keeps later math easier to trust. The class also makes quick loops feel compact, which is why it shows up so often in simple scripts and in the small helper methods that sit inside larger programs.
When the number is part of a public response, converting it to a string at the edge of the code can keep the core logic simple. That pattern works well for reports, counters, and lightweight formatting tasks. It also keeps the meaning of the number clear: the integer is still the data, while the string is only the display version.
For loops and counters, integers are also a good reminder to keep the unit close to the code. If a method counts items, indexes entries, or tracks seconds, the arithmetic stays easier to read when the variable names say what the numbers mean. That small discipline helps a lot once the code starts combining several numeric steps.