Skip to content

2. Ruby

1. Getting Started

To get started with Ruby on Ubuntu, follow these steps:

1.1 Check if Ruby is Already Installed

Ruby may already be installed on your system. You can check this by running:

Terminal window
ruby -v

If Ruby is installed, this command will display the installed version. If Ruby is not installed or if you want to install a newer version, continue to the next step.

1.2 Installing Ruby on Ubuntu

Option 1: Install Ruby from Ubuntu Repositories

You can install Ruby using the default Ubuntu package manager. This method is simple but may not provide the latest Ruby version.

Terminal window
sudo apt update
sudo apt install ruby-full

This installs the latest version of Ruby available in the Ubuntu repository.

Using a Ruby version manager like rbenv or RVM allows you to install and manage different Ruby versions.

Using rbenv:

  1. Install the necessary dependencies:

    Terminal window
    sudo apt update
    sudo apt install -y git curl
  2. Install rbenv and ruby-build (a plugin for installing Ruby):

    Terminal window
    git clone https://github.com/rbenv/rbenv.git ~/.rbenv
    echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
    echo 'eval "$(rbenv init -)"' >> ~/.bashrc
    exec $SHELL
    git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
  3. Install the desired version of Ruby (replace 3.2.0 with the version you need):

    Terminal window
    rbenv install 3.2.0
    rbenv global 3.2.0
  4. Verify the installation:

    Terminal window
    ruby -v

Using RVM:

  1. Install RVM (Ruby Version Manager):

    Terminal window
    sudo apt install curl gpg
    \curl -sSL https://get.rvm.io | bash -s stable
    source ~/.rvm/scripts/rvm
  2. Install the latest stable version of Ruby:

    Terminal window
    rvm install ruby
    rvm use ruby --default
  3. Verify the installation:

    Terminal window
    ruby -v

1.3 Install RubyGems (if not already installed)

RubyGems is Ruby’s package manager. It should be installed by default with Ruby. You can check by running:

Terminal window
gem -v

If it’s not installed, you can install it with:

Terminal window
sudo apt install rubygems

Bundler is a tool to manage project dependencies, which is often used in Ruby development.

Terminal window
gem install bundler

1.5 Write Your First Ruby Script

Create a simple Ruby script to verify that everything is working. Open a text editor (like nano) and create a file called hello.rb:

Terminal window
nano hello.rb

Add this Ruby code to the file:

puts "Hello, World!"

Save the file and exit the editor. Then, run your script with:

Terminal window
ruby hello.rb

You should see the output Hello, World! in your terminal.

1.6 Setting Up a Basic Ruby Project

If you want to set up a new Ruby project, follow these steps:

  1. Create a directory for your project:

    Terminal window
    mkdir my_ruby_project
    cd my_ruby_project
  2. Initialize the project with Bundler:

    Terminal window
    bundle init

    This creates a Gemfile where you can define your project’s dependencies.

  3. Add dependencies in your Gemfile (optional). For example, to add the Sinatra web framework:

    # Gemfile
    source "https://rubygems.org"
    gem "sinatra"
  4. Install the dependencies:

    Terminal window
    bundle install

1.7 Explore Ruby Documentation

Ruby comes with excellent documentation. To learn about any built-in class or method, use the ri command. For example:

Terminal window
ri Array

This displays detailed information about Ruby’s Array class.

You can also explore Ruby’s official documentation at https://ruby-doc.org/.


2. Control Structures in Ruby

2.1 Conditional Statements

  • if, elsif, else: These are the most basic control structures for conditional execution.

    age = 18
    if age > 18
    puts "Adult"
    elsif age == 18
    puts "Just turned adult"
    else
    puts "Minor"
    end
  • One-liner if: Ruby allows you to write one-liner conditionals.

    puts "Adult" if age > 18
  • unless: The opposite of if, it executes code only if the condition is false.

    puts "Minor" unless age >= 18
  • Ternary Operator (?:): A shorthand for if/else.

    status = age >= 18 ? "Adult" : "Minor"

2.2 Loops

  • while: Repeats while the condition is true.

    i = 0
    while i < 5
    puts i
    i += 1
    end
  • until: The opposite of while. Loops until the condition becomes true.

    i = 0
    until i == 5
    puts i
    i += 1
    end
  • for: Iterates over a range or collection.

    for i in 1..5
    puts i
    end
  • each: Ruby’s preferred way to loop over collections like arrays.

    [1, 2, 3].each do |num|
    puts num
    end

2.3 Loop Control

  • next: Skips to the next iteration.

    (1..5).each do |i|
    next if i == 3
    puts i
    end
  • break: Exits the loop entirely.

    (1..5).each do |i|
    break if i == 3
    puts i
    end
  • redo: Restarts the loop without checking the condition.

    i = 0
    while i < 5
    i += 1
    redo if i == 3 # Infinite loop on redo for i == 3
    puts i
    end

2.4 Case Statement

Similar to a switch statement in other languages.

age = 18
case age
when 0..12
puts "Child"
when 13..17
puts "Teenager"
when 18
puts "Adult, just turned 18"
else
puts "Adult"
end

3. Data Structures in Ruby

3.1 Scalars

  • Integer, Float, String: These are scalar types representing single values.

    number = 42
    price = 19.99
    name = "Ruby"

3.2 Arrays

  • An array is an ordered collection of objects, indexed by integers starting at 0.

  • Arrays are mutable, meaning their contents can be changed.

    fruits = ["apple", "banana", "cherry"]
    puts fruits[0] # Outputs "apple"
    fruits << "orange" # Adds an element to the array
  • Iterating over arrays:

    fruits.each do |fruit|
    puts fruit
    end

3.3 Hashes

  • Hashes (similar to dictionaries in other languages) store key-value pairs.

  • Keys can be any object, though symbols (:key) are often used.

    person = {name: "John", age: 25, city: "New York"}
    puts person[:name] # Outputs "John"
    person[:age] = 26 # Modifies the value for :age
  • Iterating over hashes:

    person.each do |key, value|
    puts "#{key}: #{value}"
    end

3.4 Ranges

  • Ranges represent sequences. They can be used to iterate or define sequences of numbers, characters, or objects.

    (1..5).each do |i|
    puts i
    end
    • Inclusive Range (..): Includes the last element.

      (1..5).to_a # [1, 2, 3, 4, 5]
    • Exclusive Range (...): Excludes the last element.

      (1...5).to_a # [1, 2, 3, 4]

3.5 Symbols

  • Symbols are immutable, reusable constants represented by a colon (:) followed by a name.

  • Often used as keys in hashes or identifiers.

    :name
    • Difference between strings and symbols: Symbols are more memory-efficient for things like hash keys because they are immutable and reused across the application.

3.6 Sets

  • Sets are unordered collections of unique elements, similar to arrays but without duplicates.

    require 'set'
    s = Set.new([1, 2, 3, 4])
    s.add(2) # Adding a duplicate does nothing

3.7 Structs

  • A Struct is a quick way to define simple classes with attributes.

    Person = Struct.new(:name, :age)
    john = Person.new("John", 25)
    puts john.name # Outputs "John"