Ruby
Basic Ruby Syntax
Ruby is a dynamic, object-oriented programming language known for its simplicity and productivity. In this section, we’ll cover the basic syntax of Ruby to help you get started.
1. Comments
In Ruby, you can add comments using the # symbol. Comments are ignored by the Ruby interpreter and are useful for documenting your code.
# This is a single-line comment
=begin
This is a
multi-line comment
=end
2. Output
You can display output in Ruby using the puts (put string) or print methods.
puts "Hello, Ruby!" # Prints with a newline
print "Hello, Ruby!" # Prints without a newline
3. Variables and Data Types
Ruby is dynamically typed, meaning you don’t need to declare the data type of a variable explicitly.
name = "John" # String
age = 30 # Integer
height = 6.2 # Float
is_student = true # Boolean
4. Strings
Ruby supports single-quoted (’) and double-quoted (”) strings. Double-quoted strings allow for string interpolation.
single_quoted = 'This is a single-quoted string.'
double_quoted = "Hello, #{name}!" # String interpolation
5. Numbers
Ruby supports integers and floating-point numbers.
integer_number = 42
float_number = 3.14
6. Arrays
Arrays are ordered collections of elements, and they can contain different data types.
fruits = ["apple", "banana", "cherry"]
7. Hashes
Hashes, also known as dictionaries or associative arrays, store key-value pairs.
person = {
"name" => "John",
"age" => 30,
}
8. Control Structures
Ruby provides common control structures like if, else, elsif, unless, case, and loops (while, until, for, each).
if age >= 18
puts "You are an adult."
else
puts "You are a minor."
end
9. Functions (Methods)
You can define functions using the def keyword. Ruby functions return the result of the last executed statement.
def greet(name)
"Hello, #{name}!"
end
puts greet("Alice") # Outputs: Hello, Alice!
10. Symbols
Symbols are lightweight strings often used as keys in hashes.
:my_symbol
11. Classes and Objects
Ruby is an object-oriented language, and you can define classes and create objects.
class Person
def initialize(name)
@name = name
end
def say_hello
"Hello, #{@name}!"
end
end
john = Person.new("John")
puts john.say_hello # Outputs: Hello, John!
12. Exception Handling
Ruby uses begin, rescue, and end for exception handling.
begin
result = 10 / 0
rescue ZeroDivisionError
puts "Error: Division by zero!"
end
13. Symbols and Blocks
Symbols are often used in Ruby for efficiency, and blocks are used for defining anonymous functions.
# Symbol
:my_symbol
# Block
[1, 2, 3].each do |number|
puts number
end
Ruby Functions
n Ruby, functions are known as methods, and they play a crucial role in organizing and encapsulating code. In this section, we’ll cover the basic syntax of Ruby methods, including how to define them, work with arguments, return values, and use procs and blocks.
1. Defining Methods
In Ruby, you define methods using the def keyword, followed by the method name, parentheses for arguments (if any), and an end to signify the method’s body.
def greet(name)
"Hello, #{name}!"
end
2. Calling Methods
To call a method, use its name followed by parentheses containing the arguments (if any).
result = greet("Alice")
puts result # Outputs: Hello, Alice!
3. Method Arguments
Ruby methods can take zero or more arguments. You can define methods with required, optional, or default arguments.
def add(x, y)
x + y
end
puts add(2, 3) # Outputs: 5
Optional Arguments
def greet(name, greeting = "Hello")
"#{greeting}, #{name}!"
end
puts greet("Bob") # Outputs: Hello, Bob!
puts greet("Alice", "Hi") # Outputs: Hi, Alice!
Default Arguments
def divide(x, y = 1)
x / y
end
puts divide(6) # Outputs: 6
puts divide(6, 2) # Outputs: 3
4. Return Values
Ruby methods return the result of the last executed statement by default. However, you can use the return keyword to explicitly return a value.
def add(x, y)
result = x + y
return result
end
sum = add(2, 3)
puts sum # Outputs: 5
5. Procs
A proc is an object that holds a block of code. You can create a proc using the Proc.new or -> syntax. Procs can be stored in variables and passed as arguments to methods.
my_proc = Proc.new { |x| x * 2 }
puts my_proc.call(3) # Outputs: 6
6. Blocks
Blocks are chunks of code enclosed within do…end or curly braces {…}. They are often used with methods that yield control to the block.
[1, 2, 3].each do |number|
puts number
end
You can define methods that accept blocks using the yield keyword:
def say_hello
puts "Hello!"
yield if block_given?
end
say_hello do
puts "Block executed."
end
# Outputs:
# Hello!
# Block executed.
In Ruby, blocks are commonly used for iterators, custom control structures, and working with collections like arrays and hashes.
Understanding Ruby’s method syntax, argument handling, return values, procs, and blocks is essential for effective Ruby programming. These features make Ruby a versatile language, especially when used in conjunction with libraries and frameworks like Ruby on Rails.
Ruby Classes
Classes are fundamental in Ruby for creating objects and organizing code. In this section, we’ll cover the basic syntax of Ruby classes, including constructors, properties (attributes), methods, inheritance, overriding methods, and the concept of static methods and properties.
1. Basic Syntax
To define a class in Ruby, you use the class keyword, followed by the class name in CamelCase. The class’s code block contains its properties and methods.
class Person
# Properties and methods go here
end
2. Constructors
In Ruby, the constructor method is named initialize. It’s automatically called when an instance of the class is created using new.
class Person
def initialize(name, age)
@name = name
@age = age
end
end
person = Person.new("Alice", 30)
3. Properties, Getters, and Setters
Properties in Ruby are instance variables, typically prefixed with @. To access them, you can create getter and setter methods.
class Person
def initialize(name)
@name = name
end
# Getter method
def name
@name
end
# Setter method
def name=(new_name)
@name = new_name
end
end
person = Person.new("Alice")
puts person.name # Outputs: Alice
person.name = "Bob"
puts person.name # Outputs: Bob
You can also use Ruby’s built-in attr_reader, attr_writer, or attr_accessor to generate getter and setter methods automatically.
class Person
attr_reader :name
attr_writer :name
# or attr_accessor :name for both getter and setter
def initialize(name)
@name = name
end
end
4. Methods
Methods in Ruby are defined within the class block. You can call them on instances of the class.
class Person
def initialize(name)
@name = name
end
def greet
"Hello, #{@name}!"
end
end
person = Person.new("Alice")
puts person.greet # Outputs: Hello, Alice!
5. Inheritance
Ruby supports single inheritance, allowing a class to inherit properties and methods from a parent class. Use the < symbol to indicate inheritance.
class Student < Person
def initialize(name, school)
super(name)
@school = school
end
end
student = Student.new("Bob", "High School")
puts student.greet # Outputs: Hello, Bob!
6. Overriding Methods
Inherited methods can be overridden by defining a method with the same name in the child class. To call the parent class’s method, use the super keyword.
class Student < Person
def greet
"Hi, I'm a student named #{@name}!"
end
end
student = Student.new("Charlie", "College")
puts student.greet # Outputs: Hi, I'm a student named Charlie!
7. Static Methods and Properties
In Ruby, class methods are defined using the self keyword within the class. They are called on the class itself, not on instances.
class MathUtils
def self.square(x)
x * x
end
end
result = MathUtils.square(5)
puts result # Outputs: 25
Class variables are shared across all instances of a class. They are prefixed with @@.
class Counter
@@count = 0
def initialize
@@count += 1
end
def self.total_count
@@count
end
end
Counter.new
Counter.new
puts Counter.total_count # Outputs: 2
Understanding classes, constructors, properties, methods, inheritance, method overriding, and class-level methods and properties is essential for building robust and organized Ruby applications. Classes are at the core of object-oriented programming in Ruby, allowing you to create reusable and modular code.
Ruby CLI
Running Ruby Scripts
To run Ruby scripts from the command line, use the ruby command followed by the script’s filename. For example:
ruby my_script.rb
You can also run one-liner Ruby code directly from the command line using the -e option:
ruby -e 'puts "Hello, World!"'
Commands for Working with Gems and Gemfiles
1. Installing Gems
To install a Ruby gem, use the gem install command followed by the gem’s name:
gem install gem_name
2. Listing Installed Gems
You can list all the installed gems using:
gem list
3. Running a Ruby Script with Required Gems
To run a Ruby script that depends on specific gems, use the ruby command followed by -r or —require to specify the required gems:
ruby -r gem_name my_script.rb
4. Uninstalling Gems
To uninstall a gem, use the gem uninstall command:
gem uninstall gem_name
5. Updating Gems
You can update a gem to its latest version with:
gem update gem_name
6. Creating Gemfiles
A Gemfile is used to specify project dependencies. To create one, simply create a file named Gemfile in your project’s directory.
Gemfile Syntax Here’s a basic example of a Gemfile:
# Gemfile
# Specify a gem and its version
gem 'rails', '6.1.0'
# Specify multiple gems
gem 'sqlite3', '~> 1.4'
gem 'puma', '~> 3.12'
gem 'sass-rails', '>= 6'
# Groups for different environments (e.g., development, test, production)
group :development, :test do
gem 'rspec-rails', '~> 5.0'
gem 'pry'
end
group :production do
gem 'pg', '>= 1.2', '< 2.0'
end
In the Gemfile:
Use the gem keyword followed by the gem name and its version or version constraints.
You can group gems using group to specify dependencies for different environments (e.g., development, test, production).
~>
specifies a version constraint, allowing versions up to the specified version.
>=
and <
are used to specify version ranges.
After creating or editing the Gemfile, you need to run bundle install to install the specified gems.
Running Bundler
To install all the gems listed in the Gemfile and create a Gemfile.lock file, run:
bundle install
This ensures that all project collaborators use the same gem versions.
Ruby’s CLI, along with Gemfiles and the Bundler tool, are essential for managing dependencies and running Ruby scripts and applications effectively.
Built-in Ruby Functions & Methods
1-25
Method | Purpose | Syntax | Example |
---|---|---|---|
puts | Output text to the console | puts(string) | puts "Hello, Ruby!" |
print | Output text to the console without a newline | print(string) | print "Hello, " print "Ruby!" |
gets | Read a line of text from the console | gets | name = gets.chomp |
chomp | Remove trailing newline characters from a string | chomp | input = gets.chomp |
to_i | Convert a string to an integer | to_i | num_str = "42" num = num_str.to_i |
to_f | Convert a string to a floating-point number | to_f | num_str = "3.14" num = num_str.to_f |
to_s | Convert an object to a string | to_s | num = 42 str = num.to_s |
length | Get the length of a string | length | len = "Hello".length |
upcase | Convert a string to uppercase | upcase | text = "hello".upcase |
downcase | Convert a string to lowercase | downcase | text = "HELLO".downcase |
strip | Remove leading and trailing whitespace from a string | strip | text = " hello ".strip |
split | Split a string into an array using a delimiter | split(delimiter) | words = "Hello,World".split(",") |
concat | Append one string to another | concat(string) | str1 = "Hello," str2 = " Ruby!" str1.concat(str2) |
include? | Check if a string contains another substring | include?(substring) | text = "Hello, Ruby!" text.include?("Ruby") |
empty? | Check if a string is empty | empty? | str = "" empty = str.empty? |
reverse | Reverse the characters in a string | reverse | str = "hello".reverse |
gsub | Replace all occurrences of a substring in a string | gsub(pattern, replacement) | text = "Hello, world!" text.gsub("world", "Ruby") |
match | Find the first occurrence of a pattern in a string | match(pattern) | text = "Hello, Ruby!" match = text.match(/R\w+/) |
capitalize | Capitalize the first character of a string | capitalize | text = "hello".capitalize |
join | Concatenate elements of an array into a string | join(delimiter) | arr = ["Hello", "Ruby"] str = arr.join(" ") |
to_sym | Convert a string to a symbol | to_sym | str = "variable_name" sym = str.to_sym |
rand | Generate a random number | rand(range) | random_number = rand(1..10) |
include? (Array) | Check if an array includes a specific element | include?(element) | arr = [1, 2, 3] included = arr.include?(2) |
push | Append an element to an array | push(element) | arr = [1, 2] arr.push(3) |
pop | Remove and return the last element from an array | pop | arr = [1, 2, 3] last_element = arr.pop |
26-50
Method | Purpose | Syntax | Example |
---|---|---|---|
abs | Get the absolute value of a number | abs | num = -5 num.abs |
ceil | Round a float up to the nearest integer | ceil | num = 3.2 num.ceil |
floor | Round a float down to the nearest integer | floor | num = 3.8 num.floor |
round | Round a float to the nearest integer | round | num = 3.5 num.round |
times | Execute a block of code a specified number of times | times | 3.times { puts "Hello" } |
upto | Iterate over a range of numbers | upto(limit) | `1.upto(5) { |
downto | Iterate over a range of numbers in reverse | downto(limit) | `5.downto(1) { |
map | Create a new array by applying a block to each element | `map { | e |
each | Iterate over elements of an array | `each { | e |
select | Create a new array with elements that satisfy a condition | `select { | e |
reject | Create a new array with elements that do not satisfy a condition | `reject { | e |
sort | Sort an array in ascending order | sort | arr = [3, 1, 2] sorted = arr.sort |
sort! | Sort an array in ascending order in place | sort! | arr = [3, 1, 2] arr.sort! |
reverse (Array) | Reverse the elements of an array | reverse | arr = [1, 2, 3] reversed = arr.reverse |
uniq | Remove duplicate elements from an array | uniq | arr = [1, 2, 2, 3, 3] unique = arr.uniq |
empty? (Array) | Check if an array is empty | empty? | arr = [] empty = arr.empty? |
size (Array) | Get the number of elements in an array | size | arr = [1, 2, 3] size = arr.size |
first (Array) | Get the first element of an array | first | arr = [1, 2, 3] first_element = arr.first |
last (Array) | Get the last element of an array | last | arr = [1, 2, 3] last_element = arr.last |
min (Array) | Find the minimum element in an array | min | arr = [5, 2, 8] min_value = arr.min |
max (Array) | Find the maximum element in an array | max | arr = [5, 2, 8] max_value = arr.max |
sum (Array) | Calculate the sum of elements in an array | sum | arr = [1, 2, 3] sum_result = arr.sum |
zip | Combine multiple arrays into one array of arrays | zip(array) | arr1 = [1, 2] arr2 = ['a', 'b'] zipped = arr1.zip(arr2) |
flatten | Flatten a nested array | flatten | `nested_arr = [1, [2, [3, |
51-75
Method | Purpose | Syntax | Example |
---|---|---|---|
concat (Array) | Concatenate two arrays | concat(array) | arr1 = [1, 2] arr2 = [3, 4] arr1.concat(arr2) |
join (Array) | Combine array elements into a string | join(separator) | arr = ['apple', 'banana', 'cherry'] str = arr.join(', ') |
split (String) | Split a string into an array using a delimiter | split(delimiter) | str = 'apple,banana,cherry' arr = str.split(',') |
chomp (String) | Remove trailing newline character from a string | chomp | str = "Hello\n" chomped = str.chomp |
strip (String) | Remove leading and trailing whitespaces from a string | strip | str = " Hello " stripped = str.strip |
gsub (String) | Replace all occurrences of a substring in a string | gsub(pattern, replacement) | str = 'Hello, World!' replaced = str.gsub('Hello', 'Hi') |
include? (String) | Check if a string contains another substring | include?(substring) | str = 'Hello, World!' contains = str.include?('Hello') |
upcase (String) | Convert a string to uppercase | upcase | str = 'hello' upcased = str.upcase |
downcase (String) | Convert a string to lowercase | downcase | str = 'HELLO' downcased = str.downcase |
capitalize (String) | Capitalize the first letter of a string | capitalize | str = 'hello' capitalized = str.capitalize |
reverse (String) | Reverse the characters of a string | reverse | str = 'hello' reversed = str.reverse |
strip (String) | Remove leading and trailing whitespaces from a string | strip | str = " Hello " stripped = str.strip |
count (String) | Count the occurrences of a substring in a string | count(substring) | str = 'hello world' count = str.count('l') |
delete (String) | Delete specified characters from a string | delete(characters) | str = 'hello, world!' deleted = str.delete('o') |
squeeze (String) | Remove repeated adjacent characters in a string | squeeze | str = 'bookkeeping' squeezed = str.squeeze('k') |
slice (String) | Extract a substring from a string | slice(start, length) | str = 'hello, world!' sliced = str.slice(0, 5) |
replace (String) | Replace the content of a string with another string | replace(new_string) | str = 'Hello' str.replace('Hi') |
clear (Array) | Remove all elements from an array | clear | arr = [1, 2, 3] arr.clear |
length (String) | Get the length of a string | length | str = 'Hello' length = str.length |
reverse! (String) | Reverse the characters of a string in place | reverse! | str = 'hello' str.reverse! |
insert (String) | Insert a string into another string at a specific position | insert(index, string) | str = 'hello' str.insert(3, ', world') |
slice! (String) | Extract a substring from a string in place | slice!(start, length) | str = 'hello, world!' str.slice!(0, 5) |
gsub! (String) | Replace all occurrences of a substring in a string in place | gsub!(pattern, replacement) | str = 'Hello, World!' str.gsub!('Hello', 'Hi') |
76-100
Method | Purpose | Syntax | Example |
---|---|---|---|
slice! (Array) | Remove and return elements from an array | slice!(start, length) | arr = [1, 2, 3, 4] sliced = arr.slice!(1, 2) |
pop (Array) | Remove and return the last element from an array | pop | arr = [1, 2, 3] last = arr.pop |
shift (Array) | Remove and return the first element from an array | shift | arr = [1, 2, 3] first = arr.shift |
unshift (Array) | Add one or more elements to the beginning of an array | unshift(element1, element2, ...) | arr = [2, 3] arr.unshift(1) |
push (Array) | Add one or more elements to the end of an array | push(element1, element2, ...) | arr = [1, 2] arr.push(3, 4) |
compact (Array) | Remove nil values from an array | compact | arr = [1, nil, 2, nil] arr.compact |
uniq (Array) | Remove duplicate elements from an array | uniq | arr = [1, 2, 1, 3, 2] unique = arr.uniq |
sort (Array) | Sort elements in an array | sort | arr = [3, 1, 2] sorted = arr.sort |
max (Array) | Find the maximum value in an array | max | arr = [3, 1, 2] maximum = arr.max |
min (Array) | Find the minimum value in an array | min | arr = [3, 1, 2] minimum = arr.min |
reverse (Array) | Reverse the order of elements in an array | reverse | arr = [1, 2, 3] reversed = arr.reverse |
include? (Array) | Check if an array includes a specific element | include?(element) | arr = [1, 2, 3] includes = arr.include?(2) |
each_with_index (Array) | Iterate through array elements with their indices | each_with_index | `arr = [‘a’, ‘b’, ‘c’] arr.each_with_index { |
map (Array) | Create a new array by applying a block to each element | `map { | element |
select (Array) | Filter elements in an array based on a condition | `select { | element |
reject (Array) | Filter elements in an array based on a condition (opposite of select ) | `reject { | element |
find (Array) | Find the first element that matches a condition | `find { | element |
reduce (Array) | Combine elements in an array with a binary operation | `reduce(initial) { | memo, element |
join (Array) | Combine array elements into a string with a separator | join(separator) | arr = ['apple', 'banana', 'cherry'] str = arr.join(', ') |
empty? (Array) | Check if an array is empty | empty? | `arr = [] empty |