Contents
Basic Concepts
Ruby Keywords
Keywords or reserved words are special words in a programming language that have predefined meanings and are used for certain internal processes. These words cannot be used as identifiers such as variable names, object names, or constants. Attempting to use these reserved words as identifiers will result in a compile-time error.
Example of Invalid Use of Keywords
# Ruby program to illustrate Keywords
# This is an incorrect use of the keyword 'if'
# It cannot be used as a variable name
if = 30
# Here 'if' and 'end' are keywords used incorrectly
# Using them will result in a syntax error
if if >= 18
puts "You are eligible to drive."
end
Compile-Time Error:
Error(s), warning(s):
example.rb:4: syntax error, unexpected '='
if = 30
^
example.rb:9: syntax error, unexpected '>='
if if >= 18
^
example.rb:11: syntax error, unexpected keyword_end, expecting end-of-input
Common Ruby Keywords
Ruby has a total of 41 reserved keywords. Here are some of the most common ones and their uses:
Keyword | Description |
---|---|
__ENCODING__ | The script encoding of the current file. |
__LINE__ | The line number in the current file. |
__FILE__ | The path to the current file. |
BEGIN | Runs code before any other in the current file. |
END | Runs code after all other code in the current file. |
alias | Creates an alias for a method. |
and | Logical AND with lower precedence than && . |
class | Defines a new class. |
def | Defines a method. |
do | Begins a block of code. |
end | Ends a syntax block such as a class, method, or loop. |
if | Conditional statement. |
module | Defines a module. |
next | Skips to the next iteration of a loop. |
nil | Represents “no value” or “undefined”. |
return | Exits from a method and optionally returns a value. |
self | Refers to the current object. |
true | Boolean true value. |
while | Creates a loop that executes while a condition is true. |
Example of Using Keywords Correctly
Here’s a simple example demonstrating the correct use of some Ruby keywords:
# Ruby program to illustrate the use of Keywords
#!/usr/bin/ruby
# Defining a class named 'Person'
class Person
# Defining a method using 'def' keyword
def introduce
# Printing a statement using 'puts'
puts "Hello! I'm learning Ruby."
end
# End of the method
end
# End of the class
end
# Creating an object of the class 'Person'
student = Person.new
# Calling the method using the object
student.introduce
Output:
Hello! I'm learning Ruby.
Ruby Data Types
In Ruby, data types represent various kinds of data such as text, numbers, symbols, arrays, etc. Since Ruby is a pure Object-Oriented Language, all data types are based on classes. Here are the primary data types in Ruby:
1. Numbers
2. Boolean
3. Strings
4. Hashes
5. Arrays
6. Symbols
1. Numbers: A number is generally defined as a sequence of digits, which may include a dot for decimal places. Ruby supports both integer and floating-point numbers. Depending on their size, numbers can be categorized into Fixnum
and Bignum
. However, in modern Ruby versions, they have been unified under the Integer
class.
Example:
# Ruby program to illustrate Numbers Data Type
# Float type
distance = 0.2
# Both integer and float type
time = 15.0 / 3600
speed = distance / time
puts "The average speed of the cyclist is #{speed} km/h"
Output:
The average speed of the cyclist is 48.0 km/h
2. Boolean: The Boolean data type represents two values: true
or false
. This data type is used for simple true/false conditions.
Example:
# Ruby program to illustrate Boolean Data Type
if false
puts "This won't be printed!"
else
puts "This is False!"
end
if nil
puts "nil is True!"
else
puts "nil is False!"
end
if 1
puts "1 is True!"
else
puts "1 is False!"
end
Output:
This is False!
nil is False!
1 is True!
3. Strings: A string is a collection of characters enclosed within either single ('
) or double ("
) quotes. Double-quoted strings allow for string interpolation and special character sequences, while single-quoted strings only support limited escape sequences.
Example:
# Ruby program to illustrate Strings Data Type
puts "Ruby String Data Type"
puts 'Escape using "\\"'
puts 'It\'s a beautiful day!'
Output:
Ruby String Data Type
Escape using "\"
It's a beautiful day!
4. Hashes: A hash is a collection of key-value pairs, similar to a dictionary in Python or an associative array in PHP. Keys and values are separated by =>
and each pair is enclosed within curly braces {}
.
Example:
# Ruby program to illustrate Hashes Data Type
colors = { "red" => "#FF0000", "green" => "#00FF00", "blue" => "#0000FF" }
colors.each do |color, hex|
puts "#{color} has hex value #{hex}"
end
Output:
red has hex value #FF0000
green has hex value #00FF00
blue has hex value #0000FF
5. Arrays: An array is an ordered collection of elements, which can contain data of any type. Elements are separated by commas and enclosed within square brackets []
. Arrays in Ruby can hold mixed data types.
Example
# Ruby program to illustrate Arrays Data Type
data = ["Alice", 25, 5.5, "Hello, world!", "last item"]
data.each do |element|
puts element
end
Output:
Alice
25
5.5
Hello, world!
last item
6. Symbols: Symbols are lightweight, immutable strings. They are used instead of strings in situations where memory optimization is crucial. A symbol is prefixed with a colon (:
).
Example:
# Ruby program to illustrate Symbols Data Type
countries = { :us => "United States", :ca => "Canada", :fr => "France" }
puts countries[:us]
puts countries[:ca]
puts countries[:fr]
Output:
United States
Canada
France
Types of Variables in Ruby
In Ruby, there are four main types of variables, each serving different purposes and having different scopes. Each type is distinguished by a special character at the beginning of the variable name.
Symbol | Type of Variable |
---|---|
[a-z] or _ | Local Variable |
@ | Instance Variable |
@@ | Class Variable |
$ | Global Variable |
1. Local Variables: Local variables in Ruby start with a lowercase letter (a-z
) or an underscore (_
). They are restricted to the scope in which they are defined (e.g., inside a method or a block). Local variables do not need to be initialized before use.
Example:
# Ruby program to illustrate Local Variables
# Local variables
name = "Alice"
_age = 30
puts "Name: #{name}"
puts "Age: #{_age}"
Output:
Name: Alice
Age: 30
2. Instance Variables: Instance variables start with an @
sign. They belong to a specific instance of a class and are accessible across different methods within that instance. Each instance of the class can have different values for its instance variables. Uninitialized instance variables have a nil
value by default.
Example:
# Ruby program to illustrate Instance Variables
class Book
def initialize(title, author)
# Instance variables
@title = title
@auth_name = author
end
def display_info
puts "Title: #{@title}"
puts "Author: #{@auth_name}"
end
end
# Creating objects
book1 = Book.new("Ruby Programming", "John Doe")
book2 = Book.new("Learning Ruby", "Jane Doe")
# Calling methods
book1.display_info
book2.display_info
Output:
Title: Ruby Programming
Author: John Doe
Title: Learning Ruby
Author: Jane Doe
3. Class Varia: Class variables start with @@
and are shared across all instances of a class. They belong to the class itself rather than any individual instance. Class variables must be initialized before they are used. An uninitialized class variable will raise an error.
Example:
# Ruby program to illustrate Class Variables
class Library
# Class variable
@@book_count = 0
def initialize(title)
# Instance variable
@title = title
end
def display_title
puts "Book Title: #{@title}"
end
def add_book
# Increment the class variable
@@book_count += 1
puts "Total books: #@@book_count"
end
end
# Creating objects
book1 = Library.new("The Art of Ruby")
book2 = Library.new("Ruby on Rails Guide")
# Calling methods
book1.display_title
book1.add_book
book2.display_title
book2.add_book
Output:
Book Title: The Art of Ruby
Total books: 1
Book Title: Ruby on Rails Guide
Total books: 2
4. Global Variables: Global variables start with a $
sign and are accessible from anywhere in the Ruby program. They are not limited to a specific class or scope. By default, an uninitialized global variable has a nil
value. However, excessive use of global variables can make code difficult to debug and maintain.
Example:
# Ruby program to illustrate Global Variables
# Global variable
$global_count = 5
class FirstClass
def display_count
puts "Global count in FirstClass: #$global_count"
end
end
class SecondClass
def display_count
puts "Global count in SecondClass: #$global_count"
end
end
# Creating objects
obj1 = FirstClass.new
obj2 = SecondClass.new
# Calling methods
obj1.display_count
obj2.display_count
Output:
Global count in FirstClass: 5
Global count in SecondClass: 5
Global Variable in Ruby
Global variables have a global scope, meaning they are accessible from anywhere in a program. Modifying global variables from any point in the code has implications across the entire program. Global variables are always denoted with a dollar sign ($
). If a variable needs to be shared across multiple classes, defining it as a global variable ensures it can be accessed from all classes. By default, an uninitialized global variable has a nil
value, which can lead to confusing and complex code. Global variables can be modified from any part of the program.
Syntax:
$global_variable = 5
Example:
# Ruby program demonstrating global variables
# Defining a global variable
$global_variable = 20
# Defining first class
class FirstClass
def display_global
puts "Global variable in FirstClass is #$global_variable"
end
end
# Defining second class
class SecondClass
def display_global
puts "Global variable in SecondClass is #$global_variable"
end
end
# Creating instances of both classes
first_instance = FirstClass.new
first_instance.display_global
second_instance = SecondClass.new
second_instance.display_global
Output:
Global variable in FirstClass is 20
Global variable in SecondClass is 20
In the above example, a global variable is defined with the value 20
, and it can be accessed in both classes.
Another Example:
# Ruby program to demonstrate global variables across methods and classes
$global_variable1 = "Hello"
class SampleClass
def show_global_in_instance_method
puts "Global variables are accessible here: #{$global_variable1}, #{$another_global_var}"
end
def self.set_global_in_class_method
$another_global_var = "World"
puts "Global variables are accessible here: #{$global_variable1}"
end
end
# Using the class method
SampleClass.set_global_in_class_method
# Creating an object and using the instance method
sample_object = SampleClass.new
sample_object.show_global_in_instance_method
Output:
Global variables are accessible here: Hello
Global variables are accessible here: Hello, World
Literal
In Ruby, a literal is any constant value that can be assigned to a variable. We use literals whenever we type an object directly into the code. Ruby literals are similar to those in other programming languages, with some differences in syntax and functionality.
Types of Ruby Literals
Ruby supports various types of literals:
1. Booleans and nil
2. Numbers
3. Strings
4. Symbols
5. Ranges
6. Arrays
7. Hashes
8. Regular Expressions
1. Booleans and nil: Booleans are constants that represent the truth values true
and false
. nil
is another constant that represents an “unknown” or “empty” value, and it behaves similarly to false
in conditional expressions.
Example:
# Boolean literals demonstration
puts(5 + 2 == 7) # true
puts(5 - 3 != 2) # false
puts(nil == false) # false
Output:
true
false
false
2. Numbers: Ruby supports different types of numbers, including integers and floating-point numbers. You can write numbers of any size, using underscores (_
) for readability. Ruby allows various numerical formats, including decimal, hexadecimal, octal, and binary.
Example:
# Number literals demonstration
puts("Sum: ", 100 + 2_00 + 300) # underscores for readability
puts("Hexadecimal:", 0x1A) # hexadecimal
puts("Octal:", 0o56) # octal
puts("Decimal:", 123) # decimal
puts("Binary:", 0b1101) # binary
puts("Float:", 1.234E2) # scientific notation
Output:
Sum: 600
Hexadecimal: 26
Octal: 46
Decimal: 123
Binary: 13
Float: 123.4
3. Strings: Strings in Ruby can be enclosed in either double quotes (" "
) or single quotes (' '
). Double-quoted strings support interpolation and special characters, while single-quoted strings only support limited escape sequences.
Example:
# String literals demonstration
puts("The result of 3 + 4 is: #{3 + 4}") # string interpolation
puts("Hello\nWorld") # new line in double quotes
puts('Hello\nWorld') # no new line in single quotes
Output:
The result of 3 + 4 is: 7
Hello
World
Hello\nWorld
4. Symbols: A symbol in Ruby is a lightweight, immutable string used as an identifier. Symbols are created using a colon (:
) and are never garbage-collected, making them memory-efficient for repeated use.
Example:
# Symbol demonstration
puts(:user_id) # simple symbol
puts(:"user#{42}") # symbol with interpolation
Output:
user_id
user42
5. Ranges: Ranges represent a set of values between a starting and an ending point. They can include numbers, characters, or other objects. Ranges can be constructed using the ..
(inclusive) or ...
(exclusive) operators.
Example:
# Range literals demonstration
for i in 1..4 do
puts(i)
end
puts("Exclusive range:", (1...4).to_a)
Output:
1
2
3
4
Exclusive range: [1, 2, 3]
6. Arrays: An array is a collection of objects in Ruby, enclosed within square brackets ([ ]
). Arrays can contain objects of different data types, and elements are separated by commas.
Example:
# Array demonstration
fruits = ['apple', 'banana', 'cherry']
puts(fruits[0]) # accessing the first element
puts(fruits[1..2]) # accessing a range of elements
puts("Negative index:", fruits[-1]) # accessing the last element
Output:
apple
banana
cherry
Negative index: cherry
7. Hashes: A hash is a collection of key-value pairs, similar to dictionaries in other languages. Hashes are defined using curly braces ({ }
), and symbols can be used as keys for efficiency.
Example:
# Hash demonstration
person = { name: "Alice", age: 30, city: "Wonderland" }
# Accessing hash elements
puts(person[:name])
puts(person[:age])
# Iterating over the hash
person.each do |key, value|
puts("#{key} => #{value}")
end
Output:
Alice
30
name => Alice
age => 30
city => Wonderland
8. Regular Expressions: Ruby supports regular expressions (regex) for pattern matching. Regular expressions are defined using forward slashes (/pattern/
) or %r{pattern}
.
Example:
# Regular expression demonstration
line1 = "The quick brown fox"
line2 = "Jumps over the lazy dog"
# Checks if 'quick' is in line1
if (line1 =~ /quick/)
puts line1
end
# Checks if 'lazy' is in line2 using %r{} format
if (line2 =~ %r{lazy})
puts line2
end
# Checks if 'rabbit' is in line2
if (line2 =~ /rabbit/)
puts line2
else
puts "No match found"
end
Output:
The quick brown fox
Jumps over the lazy dog
No match found
Ruby Directories
Working with Directories in Ruby
A directory is a location where files can be stored. In Ruby, the Dir
class and the FileUtils
module provide various methods for managing directories, while the File
class handles file operations. Double dot (..
) refers to the parent directory, and single dot (.
) refers to the current directory itself.
The Dir Class
The Dir
class allows access to and manipulation of directory structures in Ruby. It includes methods for listing directory contents, creating directories, changing directories, and more.
Features of the Dir Class
1. Creating Directories: The mkdir
method is used to create a new directory. It returns 0
if the directory is successfully created.
Syntax:
Dir.mkdir "directory_name"
Examples:
# Creating a directory named "my_folder"
result = Dir.mkdir "my_folder"
# Output the result
puts result
Output:
2. Checking Directories: The exist?
method checks if a directory exists.
Syntax:
Dir.exist? "directory_name"
Example:
# Create a directory named "my_folder"
Dir.mkdir("my_folder")
# Check if the directory exists
puts Dir.exist?("my_folder")
Output:
true
- The
empty?
method checks if a directory is empty.
Syntax:
Dir.empty? "directory_name"
3. Working with Directories
- The
new
method creates a new directory object (the directory should already exist).
Syntax:
obj = Dir.new("directory_name")
- The
pwd
method returns the current working directory.
Syntax:
Dir.pwd
Example:
# Create a directory named "example_folder"
Dir.mkdir("example_folder")
# Print the current working directory
puts Dir.pwd
Output:
/path/to/current/directory
- The
home
method returns the home directory of the current user.
Syntax:
Dir.home
# Print the home directory
puts Dir.home
Output:
/Users/username
- The
path
method returns the path of a directory object.
Syntax:
d = Dir.new("directory_name")
d.path
Output:
Odd
Example:
# Create a directory and get its path
Dir.mkdir("example_folder")
obj = Dir.new("example_folder")
puts obj.path
Output:
example_folder
- The
getwd
method returns the path of the current directory.
Syntax:
Dir.getwd
Example:
/path/to/current/directory
- The
chdir
method changes the current working directory.
Syntax:
Dir.chdir("directory_name")
Example:
# Create directories
Dir.mkdir("/workspace/folder1")
Dir.mkdir("/workspace/folder2")
# Change to folder2
Dir.chdir("/workspace/folder2")
puts Dir.pwd
Output:
/workspace/folder2
- The
entries
method lists all files and folders in a directory.
Syntax:
Dir.entries("directory")
Example:
# Create a directory and subdirectories
Dir.mkdir("main_folder")
Dir.chdir("main_folder")
Dir.mkdir("subfolder1")
Dir.mkdir("subfolder2")
# List all files and folders
puts Dir.entries(".")
Output:
.
..
subfolder1
subfolder2
- The
glob
method lists files matching a certain pattern.
Syntax:
Dir.glob("pattern")
Example:
# Create files and folders
Dir.mkdir("sample_folder")
Dir.chdir("sample_folder")
Dir.mkdir("test")
Dir.mkdir("demo.rb")
Dir.mkdir("script.rb")
# List files matching patterns
puts Dir.glob("*.rb")
Output:
demo.rb
script.rb
4. Removing Directories: Methods like rmdir
, delete
, and unlink
are used to remove directories.
Syntax:
Dir.delete "directory_name"
Dir.rmdir "directory_name"
Dir.unlink "directory_name"
Example:
# Create a directory
Dir.mkdir("temp_folder")
puts Dir.exist?("temp_folder")
# Remove the directory
Dir.rmdir("temp_folder")
puts Dir.exist?("temp_folder")
Output:
true
false
5. Creating Nested Directories: The mkdir_p
method from the FileUtils
module creates a directory and all its parent directories.
Syntax:
FileUtils.mkdir_p 'directory_path'
Example:
require "fileutils"
# Create nested directories
FileUtils.mkdir_p "parent/child/grandchild"
# Check existence
Dir.chdir("parent/child")
puts Dir.exist?("grandchild")
Output:
true
6. Moving Files and Folders: The mv
method from the FileUtils
module is used to move files or directories.
Syntax:
FileUtils.mv("source", "destination")
Example:
require "fileutils"
# Create directories
Dir.mkdir "source_folder"
Dir.mkdir "destination_folder"
# Move source_folder into destination_folder
FileUtils.mv("source_folder", "destination_folder")
# Check if the move was successful
Dir.chdir("destination_folder")
puts Dir.exist?("source_folder")
Output:
true
7. Copying Files: The cp
method from the FileUtils
module copies files from one location to another.
Syntax:
FileUtils.cp("source", "destination")
Example:
require "fileutils"
# Copy file.txt from source_folder to destination_folder
FileUtils.cp("source_folder/file.txt", "destination_folder")
# Check if the file exists in the destination
Dir.chdir("destination_folder")
puts File.exist?("file.txt")
Output:
true