Labs ICT
โญ Pro Login

Numbers and Math

Arithmetic and number methods.

Numbers and Math

Ruby has integers and floats, and it auto-converts between them when needed. Basic math uses the usual operators: +, -, *, /. Integer division truncates, so 7 / 2 gives 3, not 3.5. Use ** for exponentiation and % for modulo. Numbers come with handy methods like .even?, .odd?, .times, and .between?.

# Integers and floats
a = 42
b = 3.14

# Basic math
puts 10 + 5    # => 15
puts 10 - 5    # => 5
puts 10 * 5    # => 50
puts 10 / 3    # => 3 (integer division truncates)
puts 10.0 / 3  # => 3.3333333333333335

# Exponentiation and modulo
puts 2 ** 10   # => 1024
puts 10 % 3    # => 1

# Auto-conversion
result = 10 + 0.5  # => 10.5 (Float)
puts result.class   # => Float

# Number methods
puts 42.even?      # => true
puts 42.odd?       # => false
puts 42.between?(1, 100) # => true

# .times is super useful
5.times { |i| puts "Iteration #{i}" }
# Output: 0, 1, 2, 3, 4

# Other handy methods
puts 42.to_s       # => "42"
puts "42".to_i     # => 42
puts 3.9.floor     # => 3
puts 3.2.ceil      # => 4
Try it Yourself ->

๐Ÿงช Quick Quiz

What class represents integers in Ruby?