Contents

Ruby Classes

Ruby Float Class

In Ruby, the Float class is a subclass of the Numeric class. Objects of the Float class represent real numbers using the system’s native double-precision floating-point representation.

Public Instance Methods

Arithmetic Operations

The Float class supports various arithmetic operations, including addition, subtraction, multiplication, division, modulo, and exponentiation.

  • Addition: Returns the sum of a float and a numeric value as a floating-point number.

				
					float + numeric

				
			
  • Subtraction: Returns the difference between a float and a numeric value as a floating-point number.
				
					float - numeric

				
			
  • Multiplication: Returns the product of a float and a numeric value as a floating-point number.
				
					float * numeric

				
			
  • Division: Returns the quotient of a float and a numeric value as a floating-point number.
				
					float / numeric
				
			
  • Modulo: Returns the remainder when a float is divided by a numeric value.
				
					float % numeric
				
			
  • Exponentiation: Raises the float to the power of a numeric value.
				
					float ** numeric

				
			
  • Unary Minus: Returns the negative of the float.
				
					-float
				
			

Example:

				
					a = 5.5
b = 2

# Addition
puts a + b  # Output: 7.5

# Subtraction
puts a - b  # Output: 3.5

# Multiplication
puts a * b  # Output: 11.0

# Division
puts a / b  # Output: 2.75

# Modulo
puts a % b  # Output: 1.5

# Exponentiation
puts a ** b  # Output: 30.25

# Unary Minus
puts -a  # Output: -5.5
    
				
			
Comparison Operators
  • Spaceship operator (<=>): Returns -1 if the float is less than the numeric value, 0 if they are equal, and 1 if the float is greater.

				
					float <=> numeric

				
			

Example:

				
					puts 3.2 <=> 5   # Output: -1
puts 5.0 <=> 5   # Output: 0
puts 7.4 <=> 5   # Output: 1
				
			
  • Equality (==): Returns true if the float is equal to another object.
				
					float == obj
				
			

Example:

				
					p 45.5.divmod(6)  # Output: [7, 3.5]
				
			
Other Useful Methods
  • abs: Returns the absolute value of the float.

				
					float.abs
				
			
  • eql?: Returns true if the float is equal to another object, with the same value and type.
				
					float.eql?(obj)
				
			
  • ceil: Returns the smallest integer greater than or equal to the float.
				
					float.ceil
				
			
  • divmod: Returns an array containing the quotient and remainder when divided by a numeric value.
				
					float.divmod(numeric)
				
			

Example:

				
					p 45.5.divmod(6)  # Output: [7, 3.5]
				
			
  • eql?: Returns true if the float is equal to another object, with the same value and type.
				
					float.eql?(obj)
				
			

Example:

				
					puts 5.5.eql?(5.5)  # Output: true
				
			

Output:

				
					Title: Ruby Programming
Author: John Doe
Title: Learning Ruby
Author: Jane Doe

				
			
  • finite?: Returns true if the float is a valid IEEE floating-point number.
				
					float.finite?
				
			

Example:

				
					puts 10.0.finite?  # Output: true
				
			
  • floor: Returns the largest integer less than or equal to the float.
				
					float.floor
				
			

Output:

				
					Global count in FirstClass: 5
Global count in SecondClass: 5

				
			
  • floor: Returns the largest integer less than or equal to the float.
				
					float.floor
				
			
  • infinite?: Returns nil, -1, or 1 depending on whether the float is finite, negative infinity, or positive infinity.
				
					float.infinite?
				
			

Example:

				
					puts (1.0/0.0).infinite?  # Output: 1
				
			
  • round: Rounds the float to the nearest integer or to the specified number of decimal places.
				
					float.round(digits=0)
				
			

Example:

				
					puts 5.67.round   # Output: 6
puts 5.67.round(1) # Output: 5.7
				
			
  • to_f: Returns the float itself.
				
					float.to_f
				
			
  • to_i: Truncates the float to return its integer value.
				
					float.to_i
				
			
  • zero?: Returns true if the float is 0.0.
				
					float.zero?
				
			

Example:

				
					puts 0.0.zero?  # Output: true
				
			
Constants in the Float Class
  • EPSILON: Smallest floating-point number greater than 1 (2.2204460492503131e-16).
  • MANT_DIG: Number of mantissa digits (53 by default).
  • MAX: Largest double-precision floating-point number (1.7976931348623157e+308).
  • MIN: Smallest positive normalized number (2.2250738585072014e-308).
  • \INFINITY: Represents positive infinity.
  • NAN: Represents “Not a Number.”

Ruby Integer Class

The Integer class in Ruby is the foundation for two subclasses, Bignum and Fixnum, which store whole numbers. Fixnum holds integer values within the machine’s native word size, while Bignum handles values outside the range of Fixnum. The Integer class itself inherits from the Numeric class and offers a variety of methods for performing operations on integers.

Methods in the Integer Class

1. to_i: This method returns the integer value. Its synonym is to_int.

				
					int.to_i
				
			

2. chr: This method returns the ASCII character that corresponds to the integer’s value as a string.

				
					int.chr
				
			

Example:

				
					puts 97.chr  # Output: "a"
puts 66.chr  # Output: "B"
				
			

3. downto: This method passes decreasing integer values from the receiver down to (and including) the argument, yielding each value to the block.

				
					int.downto(integer) {|i| block}

				
			

Example:

				
					5.downto(1) { |i| print "#{i} " }
# Output: 5 4 3 2 1

				
			

4. floor: This method returns the largest integer less than or equal to the receiver. It behaves similarly to to_i.

				
					int.floor
				
			

Example:

				
					puts 3.floor  # Output: 3
puts (-3.4).floor  # Output: -4
				
			

5. integer?: This method checks if the object is an integer, returning true if it is and false otherwise.

				
					int.integer?

				
			

Example:

				
					puts 5.integer?  # Output: true
puts 3.7.integer?  # Output: false

				
			

6. next and succ: These methods return the next integer, which is the current integer plus one. Both methods are synonymous.

				
					int.next
int.succ

				
			

Example:

				
					puts 7.next  # Output: 8
puts (-3).succ  # Output: -2

				
			

7. times: This method executes the block a specified number of times, passing values from 0 to int - 1.

				
					int.times { |i| block }

				
			

8. upto: This method iterates over integers from the receiver up to (and including) the specified value, yielding each number to the block.

				
					4.times { |i| print "#{i} " }
# Output: 0 1 2 3

				
			

Examples:

				
					2.upto(5) { |i| print "#{i} " }
# Output: 2 3 4 5
				
			

9. round: This method rounds the integer or float to the nearest integer. If no argument is provided, it rounds to zero decimal places.

				
					puts 10.round  # Output: 10
puts (15.67).round  # Output: 16

				
			
Additional Methods
  • to_int: Same as to_i, returns the integer value.
  • truncate: Similar to floor, it truncates any decimal part and returns an integer.
  • zero?: Returns true if the integer is zero, otherwise false.
  • odd?: Returns true if the integer is odd, otherwise false.
  • even?: Returns true if the integer is even, otherwise false.

Ruby Symbol Class

The Struct class in Ruby provides a concise way to bundle multiple attributes together, using accessor methods, without the need to define an explicit class. Each structure creates a new class with accessor methods for a predefined set of variables. A subclass of Struct is Struct::Tms.

Example:

				
					# Ruby program demonstrating Symbol objects

# A symbol representing a class
module ModuleA
  class MyClass
  end
  $sym1 = :MyClass
end

# A symbol representing a constant
module ModuleB
  MyConstant = 1
  $sym2 = :MyClass
end

# A symbol representing a method
def MyClassMethod
end
$sym3 = :MyClass

puts $sym1.object_id
puts $sym2.object_id
puts $sym3.object_id

				
			

Output:

				
					1675428
1675428
1675428

				
			

In this example, the symbol :MyClass refers to the same object, regardless of whether it’s used as a class name, constant, or method.

Class Method
  • all_symbols: Returns an array of all symbols currently available in Ruby’s symbol table.
				
					Symbol.all_symbols
				
			

Example:

				
					# Ruby program demonstrating the all_symbols method
puts Symbol.all_symbols.size  
puts Symbol.all_symbols[1, 10]

				
			

Output:

				
					3250
[:a_symbol, :another_symbol, ...]  # An example of some symbols

				
			
Instance Methods
  • id2name: Returns the string representation of a symbol.
				
					sym.id2name

				
			

Example:

				
					# Ruby program demonstrating the id2name method
p :Ruby.id2name  
p :"Hello World".id2name

				
			

Output:

				
					"Ruby"
"Hello World"
				
			
  • inspect: Returns a string representation of the symbol, prefixed with a colon.
				
					sym.inspect
				
			
Example:
				
					# Ruby program demonstrating the inspect method
p :ruby.inspect
p :"sample text".inspect
				
			

Output:

				
					":ruby"
":\"sample text\""
				
			
  • to_s: Converts the symbol to its string equivalent.
				
					sym.to_s
				
			

Example:

				
					# Ruby program demonstrating the to_s method
p :language.to_s
p :"hello world".to_s

				
			

Output:

				
					"language"
"hello world"
				
			
  • <=>: Compares two symbols after converting them to strings. Returns -1 if the first symbol is less, 0 if they are equal, and 1 if it’s greater.
				
					sym <=> other_sym
				
			
  • ==: Returns true if two symbols are the same object.
				
					# Ruby program demonstrating the <=> method
a = :ruby
b = :"programming language"
puts a <=> b  # Output: -1
puts a <=> :ruby  # Output: 0
puts b <=> a  # Output: 1

				
			
  • ==: Returns true if two symbols are the same object.
				
					# Ruby program demonstrating the == method
a = :ruby
b = :"programming language"
puts a == b  # Output: false
puts a == :ruby  # Output: true

				
			

Example:

				
					# Ruby program demonstrating the == method
a = :ruby
b = :"programming language"
puts a == b  # Output: false
puts a == :ruby  # Output: true

				
			
  • downcase: Converts all uppercase letters in the symbol to lowercase.
				
					sym.downcase
				
			

Example:

				
					# Ruby program demonstrating the downcase method
puts :"RUBY LANGUAGE".downcase

				
			
  • The entries method lists all files and folders in a directory.

Syntax:

				
					Dir.entries("directory")
				
			

Output:

				
					:"ruby language"

				
			
  • length: Returns the number of characters in the symbol.
				
					sym.length
				
			

Example:

				
					# Ruby program demonstrating the length method
puts :RubySymbol.length
				
			

Output:

				
					10
				
			
  • slice: Returns a substring or character at a given index from the symbol.
				
					sym.slice(index)
sym.slice(start, length)

				
			

Example:

				
					# Ruby program demonstrating the slice method
p :Programming.slice(2)  # Output: "o"
p :Programming.slice(0, 6)  # Output: "Progra"
				
			
  • swapcase: Swaps the case of the symbol’s characters, converting uppercase to lowercase and vice versa.
				
					swapcase: Swaps the case of the symbol’s characters, converting uppercase to lowercase and vice versa.
				
			

Example:

				
					# Ruby program demonstrating the swapcase method
p :"RubyLanguage".swapcase

				
			

Output:

				
					:"rUBYlANGUAGE"
				
			
  • upcase: Converts all lowercase letters in the symbol to uppercase.
				
					sym.upcase
				
			

Example:

				
					# Ruby program demonstrating the upcase method
p :"ruby language".upcase

				
			

Output:

				
					:"RUBY LANGUAGE"

				
			
  • to_proc: Converts the symbol into a Proc object that invokes the method represented by the symbol.
				
					sym.to_proc

				
			

Example:

				
					# Example using an array of strings
words = ["apple", "banana", "cherry"]

# Using &:symbol to convert symbol to Proc
capitalized_words = words.map(&:capitalize)

puts capitalized_words

				
			

Output:

				
					Apple
Banana
Cherry

				
			
  • to_sym: Returns the symbol itself (as it is already a symbol).
				
					sym.to_sym
				
			

Example:

				
					# Example: String to Symbol
str = "hello"
symbol = str.to_sym
puts symbol  # Output: :hello
puts symbol.class  # Output: Symbol

				
			

Output:

				
					:world
Symbol

				
			

Ruby Struct Class

The Struct class in Ruby provides a concise way to bundle multiple attributes together, using accessor methods, without the need to define an explicit class. Each structure creates a new class with accessor methods for a predefined set of variables. A subclass of Struct is Struct::Tms.

Example:

				
					# Ruby program demonstrating the use of Struct

# Creating a Struct with custom behavior
Course = Struct.new(:name, :category) do
  def details
    "This is a #{category} course on #{name}."
  end
end

# Creating an instance of the struct
course = Course.new("Ruby", "Programming")
puts course.details

				
			

Output:

				
					This is a Programming course on Ruby.
				
			
Class Method
  • new: This method creates a new class with accessor methods for the provided symbols. If the name string is omitted, an anonymous structure class is created. If a name is provided, it appears as a constant in the Struct class and must be unique, starting with a capital letter.
				
					Struct.new([name], symbol1, symbol2)
Struct.new([name], symbol1, symbol2){block}
				
			

Example:

				
					# Ruby program demonstrating Struct creation

# Creating a structure with a name in Struct
Struct.new("Course", :subject, :type)
Struct::Course.new("Ruby", "Programming")

# Creating a structure using a constant name
Course = Struct.new(:subject, :type)
p Course.new("Ruby", "Programming")

				
			

Output:

				
					#<struct Course subject="Ruby", type="Programming">
				
			
Instance Methods
  • ==: Checks for equality between two instances of the same Struct class, comparing the values of their instance variables.
				
					instance1 == instance2
				
			

Example:

  • []=: Assigns a new value to an instance variable using a symbol or index.
				
					# Ruby program demonstrating equality in Structs

Course = Struct.new(:subject, :type)
course1 = Course.new("Ruby", "Programming")
course2 = Course.new("Python", "Data Science")
course3 = Course.new("Ruby", "Programming")

puts course1 == course2  # Output: false
puts course1 == course3  # Output: true

				
			
  • each: Iterates over each instance variable’s value, passing it to the given block.
				
					instance.each { |value| block }
				
			

Example:

				
					# Ruby program demonstrating each method

Course = Struct.new(:subject, :type)
course = Course.new("Ruby", "Programming")

course.each { |value| puts value }
				
			
  • each: Iterates over each instance variable’s value, passing it to the given block.
				
					# Ruby program demonstrating each method

Course = Struct.new(:subject, :type)
course = Course.new("Ruby", "Programming")

course.each { |value| puts value }
				
			

Output:

				
					Ruby
Programming
				
			
  • each_pair: Iterates over each instance variable, passing both the name and the value to the given block.
  • each_pair: Iterates over each instance variable, passing both the name and the value to the given block.
				
					instance.each_pair { |name, value| block }
				
			

Example:

				
					# Ruby program demonstrating each_pair method

Course = Struct.new(:subject, :type)
course = Course.new("Ruby", "Programming")

course.each_pair { |name, value| puts "#{name} => #{value}" }

				
			

Output:

				
					# Ruby program demonstrating attribute assignment

Course = Struct.new(:subject, :type)
course = Course.new("Ruby", "Programming")

course[:subject] = "JavaScript"
course[1] = "Web Development"

puts course.subject  # Output: JavaScript
puts course.type     # Output: Web Development