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.
-floatExample:
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.5Comparison 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 <=> numericExample:
puts 3.2 <=> 5 # Output: -1
puts 5.0 <=> 5 # Output: 0
puts 7.4 <=> 5 # Output: 1- Equality (
==): Returnstrueif the float is equal to another object.
float == objExample:
p 45.5.divmod(6) # Output: [7, 3.5]Other Useful Methods
abs: Returns the absolute value of the float.
float.abseql?: Returnstrueif 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.ceildivmod: 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?: Returnstrueif the float is equal to another object, with the same value and type.
float.eql?(obj)Example:
puts 5.5.eql?(5.5) # Output: trueOutput:
Title: Ruby Programming
Author: John Doe
Title: Learning Ruby
Author: Jane Doefinite?: Returnstrueif the float is a valid IEEE floating-point number.
float.finite?Example:
puts 10.0.finite? # Output: truefloor: Returns the largest integer less than or equal to the float.
float.floorOutput:
Global count in FirstClass: 5
Global count in SecondClass: 5floor: Returns the largest integer less than or equal to the float.
float.floorinfinite?: Returnsnil,-1, or1depending on whether the float is finite, negative infinity, or positive infinity.
float.infinite?Example:
puts (1.0/0.0).infinite? # Output: 1round: 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.7to_f: Returns the float itself.
float.to_fto_i: Truncates the float to return its integer value.
float.to_izero?: Returnstrueif the float is 0.0.
float.zero?Example:
puts 0.0.zero? # Output: trueConstants 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_i2. chr: This method returns the ASCII character that corresponds to the integer’s value as a string.
int.chrExample:
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 14. floor: This method returns the largest integer less than or equal to the receiver. It behaves similarly to to_i.
int.floorExample:
puts 3.floor # Output: 3
puts (-3.4).floor # Output: -45. 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: false6. next and succ: These methods return the next integer, which is the current integer plus one. Both methods are synonymous.
int.next
int.succExample:
puts 7.next # Output: 8
puts (-3).succ # Output: -27. 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 3Examples:
2.upto(5) { |i| print "#{i} " }
# Output: 2 3 4 59. 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: 16Additional Methods
to_int: Same asto_i, returns the integer value.truncate: Similar tofloor, it truncates any decimal part and returns an integer.zero?: Returnstrueif the integer is zero, otherwisefalse.odd?: Returnstrueif the integer is odd, otherwisefalse.even?: Returnstrueif the integer is even, otherwisefalse.
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_idOutput:
1675428
1675428
1675428In 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_symbolsExample:
# 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 symbolsInstance Methods
id2name: Returns the string representation of a symbol.
sym.id2nameExample:
# Ruby program demonstrating the id2name method
p :Ruby.id2name
p :"Hello World".id2nameOutput:
"Ruby"
"Hello World"inspect: Returns a string representation of the symbol, prefixed with a colon.
sym.inspectExample:
# Ruby program demonstrating the inspect method
p :ruby.inspect
p :"sample text".inspectOutput:
":ruby"
":\"sample text\""to_s: Converts the symbol to its string equivalent.
sym.to_sExample:
# Ruby program demonstrating the to_s method
p :language.to_s
p :"hello world".to_sOutput:
"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: trueExample:
# Ruby program demonstrating the == method
a = :ruby
b = :"programming language"
puts a == b # Output: false
puts a == :ruby # Output: truedowncase: Converts all uppercase letters in the symbol to lowercase.
sym.downcaseExample:
# Ruby program demonstrating the downcase method
puts :"RUBY LANGUAGE".downcase- The
entriesmethod 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.lengthExample:
# Ruby program demonstrating the length method
puts :RubySymbol.lengthOutput:
10slice: 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".swapcaseOutput:
:"rUBYlANGUAGE"upcase: Converts all lowercase letters in the symbol to uppercase.
sym.upcaseExample:
# Ruby program demonstrating the upcase method
p :"ruby language".upcaseOutput:
:"RUBY LANGUAGE"to_proc: Converts the symbol into aProcobject that invokes the method represented by the symbol.
sym.to_procExample:
# Example using an array of strings
words = ["apple", "banana", "cherry"]
# Using &:symbol to convert symbol to Proc
capitalized_words = words.map(&:capitalize)
puts capitalized_wordsOutput:
Apple
Banana
Cherryto_sym: Returns the symbol itself (as it is already a symbol).
sym.to_symExample:
# Example: String to Symbol
str = "hello"
symbol = str.to_sym
puts symbol # Output: :hello
puts symbol.class # Output: SymbolOutput:
:world
SymbolRuby 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.detailsOutput:
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 theStructclass 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 sameStructclass, comparing the values of their instance variables.
instance1 == instance2Example:
[]=: 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: trueeach: 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
Programmingeach_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