Integer
Integer() Returns:
Integer · Updated March 13, 2026 · Core Classes numbers integers arithmetic precision
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)
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
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)
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)
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
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"]]
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
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
Constants
Integer::MAX # Largest integer
Integer::MIN # Smallest integer
Integers in Ruby are unlimited precision, making them perfect for mathematical calculations without overflow concerns.