Ruby has a rich set of built-in methods that can be used with integers. Here are some commonly used ones:
.jpg)
Arithmetic Methods
num1 = 10
num2 = 5
# Addition
sum = num1 + num2
# Subtraction
difference = num1 - num2
# Multiplication
product = num1 * num2
# Division
quotient = num1 / num2
# Modulo (returns the remainder)
remainder = num1 % num2
Comparison Methods
num1 = 10
num2 = 5
# Equal to
is_equal = num1 == num2
# Not equal to
is_not_equal = num1 != num2
# Greater than
is_greater_than = num1 > num2
# Less than
is_less_than = num1 < num2
# Greater than or equal to
is_greater_than_or_equal_to = num1 >= num2
# Less than or equal to
is_less_than_or_equal_to = num1 <= num2
Bitwise Methods
num1 = 10
num2 = 5
# Bitwise AND
result = num1 & num2
# Bitwise OR
result = num1 | num2
# Bitwise XOR
result = num1 ^ num2
# Bitwise NOT
result = ~num1
# Bitwise left shift
result = num1 << 1
# Bitwise right shift
result = num1 >> 1
Conversion Methods
num = 10
# Convert to binary
binary = num.to_s(2)
# Convert to octal
octal = num.to_s(8)
# Convert to hexadecimal
hexadecimal = num.to_s(16)
Formatting Methods
num = 10
# Format as a string with leading zeros
formatted_str = num.to_s.rjust(4, '0')
# Format as a string with leading spaces
formatted_str = num.to_s.rjust(4)
# Format as a string with trailing zeros
formatted_str = num.to_s.ljust(4, '0')
# Format as a string with trailing spaces
formatted_str = num.to_s.ljust(4)
Prime Number Methods
require 'prime'
num = 10
# Check if the number is prime
is_prime = Prime.prime?(num)
# Get the next prime number
next_prime = Prime.next_prime(num)
# Get the previous prime number
prev_prime = Prime.prev_prime(num)
Exponential Methods
num = 2
# Raise to a power
result = num ** 3
# Raise to a power and take the modulus
result = num ** 3 % 5
# Take the square root
square_root = Math.sqrt(num)
Range Methods
range = 1..10
# Convert range to an array
array = range.to_a
# Get the maximum value in the range
max_value = range.max
# Get the minimum value in the range
min_value = range.min
# Check if a value is within the range
within_range = range.include?(5)
Division Methods
num1 = 10
num2 = 3
# Integer division
result = num1 / num2
# Modulus (remainder) after division
remainder = num1 % num2
# Float division
result = num1.to_f / num2
Other Methods
num = 10
# Check if the number is even
is_even = num.even?
# Check if the number is odd
is_odd = num.odd?
# Check if the number is a perfect square
is_square = (Math.sqrt(num) % 1 == 0)
# Round to the nearest integer
rounded_int = num.round
These methods can be useful for working with ranges of numbers, performing division operations, and checking various properties of numbers such as evenness and perfect squares.

0 Comments