Page Content

Tutorials

Numbers In Ruby: Integers, Floats, And More To Know

Numbers in Ruby

Numbers are basic data types in Ruby and are handled as objects, exactly like all other objects. This implies that methods on numeric literals can be called directly. The language offers a number of built-in classes that are optimized for different uses and represent distinct kinds of numbers.

Ruby’s Numeric Class Hierarchy

Ruby has a hierarchy of several numeric classes:

Numeric: The abstract foundation class for all numbers is called numeric. It establishes standard numerical behaviour.

Integer: Whole numbers belong to the abstract class Integer. All integers are now members of the Integer class, however Fixnum and Bignum are still present for backward compatibility, as Fixnum and Bignum were combined into Integer in Ruby 2.4+.

  • Fixnum: The integers stored in fixnum objects fit inside a native machine word, which is usually 31 bits. These are frequently seen as instantaneous values for effectiveness.
  • Bignum: The sole restriction on the size of bignum objects is the amount of memory that may be used to represent integers. An operation on Fixnum operands is transparently transformed to Bignum if the result is too large for Fixnum, and vice versa.

Float: Float objects use the platform’s built-in double-precision floating-point representation to approximate real numbers.

There are more number classes in the standard library as well:

  • Complex for numbers that are complex, as (2+3i).
  • BigDecimal is particularly helpful for financial computations since it uses a decimal representation of real values with variable accuracy, preventing binary floating-point rounding mistakes.
  • It makes sense for fractions to be precisely represented by rational numbers, which are the quotient of two integers.

Number Literals and Representation

Integer Literals are digit sequences.

Decimal (base 10): Underscores are omitted for readability in numbers 123 and 1000.

Hexadecimal (base 16): Start with 0x or 0X (base 16).

Binary (base 2): Start with 0b or 0B in binary (base 2).

Octal (base 8): Base 8 octal numbers start with 0 and go through 0–7.

The minus symbol – is used to precede negative numbers.

You can also read What Are Variables In Ruby With The Practical Code Examples

Floating-Point Literals

Floating Point Literals contain an exponent and/or a decimal point. The decimal point must be preceded and followed by digits in Ruby (0.1 instead of.1).

0.0         # => 0.0 [8, 28, 29, 60, 61]
-3.14       # => -3.14 [8, 60, 61]
6.02e23     # => 6.02e+23 (6.02 x 10^23) 
1_000_000.01 # Underscores also work 

Basic Arithmetic Operations

Ruby’s numeric types specify common arithmetic operators. Since many of these operators are implemented as methods, classes are able to give them their own definitions.

Addition (+), Subtraction (-), Multiplication (*): These behave as expected.

Division (/): The operand type affects how this operator behaves.

  • Integer Division: An integer is the outcome of integer division if all operands are integers; any leftover is shortened and deleted.
  • Float Division: A float must be one of the parameters in order to obtain a floating-point result.

Modulo (%): returns a division’s remainder. In contrast to C and Java, Ruby always uses the same sign for the result as the second operand.

Exponentiation (**): makes the first argument stronger than the second.

Operator Precedence: Standard operator precedence norms, such as exponentiation before multiplication and multiplication before addition, are adhered to by Ruby. You can override precedence by using brackets.

You can also read Constants In Ruby: What They Are, It’s Scope And Access

Other Numeric Methods and Concepts

Numbers have numerous built-in methods for a variety of operations because Ruby is object-oriented.

Type Conversion

Converting numbers between different kinds is possible with the use of functions like to_s, to_i, to_f, to_c, and to_r.

"123".to_i    # => 123 
123.to_f      # => 123.0 
4.5.to_i      # => 4 
5.to_f        # => 5.0
2.to_s(2)     # => "10" (convert to binary string) 

Rounding Methods

The rounding functions are provided by the Numeric class and its subclasses:

  • round: Rounds to the closest whole number. 0.5 steps closer to positive infinity.
  • floor: Rounds the number down to the greatest integer that is less than or equal to it.
  • ceil: The lowest integer that is bigger than or equal to the number is returned, rounded up.
  • truncate: Rounding to zero, the fractional portion is chopped off.

Absolute Value and Sign

abs: Gives the number’s absolute value back.

<=> Operator (spaceship operator): returns -1, 0, or 1 depending on whether the first number is less than, equal to, or greater than the second.

Even and Odd Numbers: Methods for determining whether an integer object is even or odd exist:

even?: Returns true if the number is even.

odd?: Returns true if the number is odd.

Numeric Predicates

zero?: Returns true if the number is 0.

nonzero?: Returns the number if it’s not zero, otherwise nil.

integer?: Returns true if the number is an Integer.

You can also read What Are Literals In Ruby Explained With Code Examples

Numeric Iterators

Iterator methods, defined by integers and numeric objects, function similarly to loops and frequently take a block of code.

times: Uses numbers ranging from 0 to n-1 to invoke the related block n times.

upto: From the receiver to the argument, iterates upward.

downto: Iterates downhill from the argument to the receiver.

step: When working with floating-point numbers, iterates with a predetermined step increment.

Math Module: In the Math module, trigonometry, logarithms, and other mathematical functions are defined along with constants (PI, E).

Math::PI            # => 3.14159265358979 
Math::E             # => 2.71828182845905 
Math.sqrt(25.0)     # => 5.0 (square root) 
Math.log10(100.0)   # => 2.0 (base-10 logarithm)
Math.sin(Math::PI/2) # => 1.0 (sine) 

Random Numbers: You can create random numbers with the rand function.

rand(6) + 1           # => A random integer from 1 to 6 (inclusive) 
Random.new.rand(1..6) # => A random integer from a range (inclusive, Ruby 1.9.2+) 

Example Program combining Numbers and Math

This short software illustrates number iteration and fundamental maths:

# Exercise 3 Numbers and Math 

puts "I will now do some basic math:"

puts "Hens: #{25 + 30 / 6}" # => Hens: 30
puts "Roosters: #{100 - 25 * 3 % 4}" # => Roosters: 97 (25 * 3 = 75, 75 % 4 = 3, 100 - 3 = 97)

puts "Now I will count my chickens:"
puts "I have #{25 + 30 / 6} hens and #{100 - 25 * 3 % 4} roosters."

puts "Is it true that 3 + 2 < 5 - 7?"
puts 3 + 2 < 5 - 7 # => false

puts "What is 3 + 2? #{3 + 2}" # => What is 3 + 2? 5
puts "What is 5 - 7? #{5 - 7}" # => What is 5 - 7? -2

puts "Oh, that's why it's false."

puts "How about some more complex calculations?"
puts "Square root of 81: #{Math.sqrt(81)}" # => Square root of 81: 9.0
puts "2 to the power of 10: #{2**10}"     # => 2 to the power of 10: 1024

puts "Let's count up to 5:"
5.times do |i|
  puts i + 1
end
# Prints:
# 1
# 2
# 3
# 4
# 5

puts "Counting with a step:"
1.step(10, 2) {|i| print i, " " } # Prints "1 3 5 7 9 " 
puts "\n"

# Demonstrating float conversion for precise division
puts "Integer division: #{10 / 4}" # => Integer division: 2
puts "Float division: #{10.0 / 4}" # => Float division: 2.5

# Rounding examples
puts "Rounding 3.7: #{3.7.round}"   # => Rounding 3.7: 4
puts "Floor of 3.7: #{3.7.floor}"   # => Floor of 3.7: 3
puts "Ceil of 3.2: #{3.2.ceil}"     # => Ceil of 3.2: 4

# Checking even/odd
puts "Is 7 even? #{7.even?}" # => Is 7 even? false
puts "Is 6 odd? #{6.odd?}"   # => Is 6 odd? false

Output

I will now do some basic math:
Hens: 30
Roosters: 97
Now I will count my chickens:
I have 30 hens and 97 roosters.
Is it true that 3 + 2 < 5 - 7?
false
What is 3 + 2? 5
What is 5 - 7? -2
Oh, that's why it's false.
How about some more complex calculations?
Square root of 81: 9.0
2 to the power of 10: 1024
Let's count up to 5:
1
2
3
4
5
Counting with a step:
1 3 5 7 9 
Integer division: 2
Float division: 2.5
Rounding 3.7: 4
Floor of 3.7: 3
Ceil of 3.2: 4
Is 7 even? false
Is 6 odd? false

You can also read Strings In Ruby: An Object-Oriented Approach To Text

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index