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:
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.
sudo apt updatesudo apt install ruby-full
This installs the latest version of Ruby available in the Ubuntu repository.
Option 2: Install Ruby Using a Version Manager (Recommended)
Using a Ruby version manager like rbenv
or RVM
allows you to install and manage different Ruby versions.
Using rbenv
:
-
Install the necessary dependencies:
Terminal window sudo apt updatesudo apt install -y git curl -
Install
rbenv
andruby-build
(a plugin for installing Ruby):Terminal window git clone https://github.com/rbenv/rbenv.git ~/.rbenvecho 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrcecho 'eval "$(rbenv init -)"' >> ~/.bashrcexec $SHELLgit clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build -
Install the desired version of Ruby (replace
3.2.0
with the version you need):Terminal window rbenv install 3.2.0rbenv global 3.2.0 -
Verify the installation:
Terminal window ruby -v
Using RVM:
-
Install
RVM
(Ruby Version Manager):Terminal window sudo apt install curl gpg\curl -sSL https://get.rvm.io | bash -s stablesource ~/.rvm/scripts/rvm -
Install the latest stable version of Ruby:
Terminal window rvm install rubyrvm use ruby --default -
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:
gem -v
If it’s not installed, you can install it with:
sudo apt install rubygems
1.4 Install Bundler (Optional but Recommended)
Bundler is a tool to manage project dependencies, which is often used in Ruby development.
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
:
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:
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:
-
Create a directory for your project:
Terminal window mkdir my_ruby_projectcd my_ruby_project -
Initialize the project with
Bundler
:Terminal window bundle initThis creates a
Gemfile
where you can define your project’s dependencies. -
Add dependencies in your
Gemfile
(optional). For example, to add the Sinatra web framework:# Gemfilesource "https://rubygems.org"gem "sinatra" -
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:
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 = 18if age > 18puts "Adult"elsif age == 18puts "Just turned adult"elseputs "Minor"end -
One-liner
if
: Ruby allows you to write one-liner conditionals.puts "Adult" if age > 18 -
unless
: The opposite ofif
, it executes code only if the condition isfalse
.puts "Minor" unless age >= 18 -
Ternary Operator (
?:
): A shorthand forif
/else
.status = age >= 18 ? "Adult" : "Minor"
2.2 Loops
-
while
: Repeats while the condition is true.i = 0while i < 5puts ii += 1end -
until
: The opposite ofwhile
. Loops until the condition becomes true.i = 0until i == 5puts ii += 1end -
for
: Iterates over a range or collection.for i in 1..5puts iend -
each
: Ruby’s preferred way to loop over collections like arrays.[1, 2, 3].each do |num|puts numend
2.3 Loop Control
-
next
: Skips to the next iteration.(1..5).each do |i|next if i == 3puts iend -
break
: Exits the loop entirely.(1..5).each do |i|break if i == 3puts iend -
redo
: Restarts the loop without checking the condition.i = 0while i < 5i += 1redo if i == 3 # Infinite loop on redo for i == 3puts iend
2.4 Case Statement
Similar to a switch
statement in other languages.
age = 18case agewhen 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 = 42price = 19.99name = "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 fruitend
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 iend-
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"