Learn in 10 minutes

Learn in 10 minutes

Learn Ruby in 10 minutes

Ruby is a dynamic, object-oriented programming language known for its elegant syntax and developer-friendly features. This tutorial covers Ruby’s core concepts to help you quickly learn the language.

1. Writing Your First Ruby Program

Let’s start with a simple program. Create a file named hello.rb and enter the following code:

puts "Hello, World!"

Save the file and run the following command in the terminal:

ruby hello.rb

The output will be:

Hello, World!

This simple program demonstrates Ruby’s basic output functionality. The puts method is used to display text information in the console.

2. Basic Syntax

Ruby’s syntax is clean and readable, designed to be natural and intuitive.

# This is a comment
puts "Hello, World!"

Basic syntax rules in Ruby:

  • Comments: Single-line comments start with #, while multi-line comments use =begin and =end.
  • Statements: Typically one statement per line, no semicolon ; is needed at the end.
  • Code Blocks: Defined by do...end or curly braces {}.
  • Method Calls: Parentheses are optional for method calls without arguments.

Example with multi-line comments:

=begin
This is a multi-line comment,
spanning multiple lines.
=end

3. Variables and Data Types

In Ruby, variables are dynamically typed and don’t require explicit type declarations.

Basic variable naming rules:

  • Variable names can only contain letters, numbers, and underscores.
  • Variable names cannot start with a number.
  • Variable names are case-sensitive.
  • Ruby keywords cannot be used as variable names.

Ruby’s main basic data types are:

  • Integer (Integer): e.g., 42 or -10.
  • Float (Float): e.g., 3.14 or 2.5e3.
  • String (String): e.g., "hello" or 'world', using single or double quotes.
  • Boolean (Boolean): true or false.
  • Nil (Nil): Represented by nil, indicating null or no value.
  • Symbol (Symbol): e.g., :name, immutable identifiers.

3.1 Numeric Types

Ruby supports integers and floating-point numbers.

# Integer
age = 25
population = 1_000_000  # Underscores for readability

# Float
temperature = 36.5
pi = 3.14159

# Operations
puts 10 + 5   # 15
puts 10 / 3   # 3 (integer division)
puts 10.0 / 3 # 3.333... (float division)

3.2 String

Strings are sequences of characters, enclosed in single or double quotes.

single_quote = 'Single quote string'
double_quote = "Double quote string"
multiline = "This is a
multi-line string"

# String interpolation (only in double quotes)
name = "Alice"
greeting = "Hello, #{name}!"
puts greeting  # "Hello, Alice!"

String operations:

text = "Ruby programming"
puts text.length        # String length
puts text.upcase        # Convert to uppercase
puts text.downcase      # Convert to lowercase
puts text[0]            # Access first character
puts text[0..3]         # String slicing
puts text.include?("Ruby")  # Check inclusion

3.3 Boolean Type

Boolean type has two values: true and false.

is_active = true
is_complete = false

# Boolean operations
result1 = true && false  # false
result2 = true || false  # true
result3 = !true          # false

3.4 Nil Type

nil represents a null or no-value state.

value = nil

if value.nil?
  puts "Value is null"
end

3.5 Symbol

Symbols are immutable identifiers, often used as keys in hashes.

:name
:email
:created_at

# Symbols vs Strings
puts :name.object_id == :name.object_id  # true (same object)
puts "name".object_id == "name".object_id  # false (different objects)

4. Data Structures

Ruby provides several built-in data structures for storing and manipulating data.

4.1 Array

An array is an ordered collection that can hold multiple values.

numbers = [1, 2, 3, 4, 5]
numbers.push(6)        # Add element
numbers.unshift(0)     # Insert at beginning
numbers.delete(3)      # Remove specific value
numbers[0] = 10        # Modify element
puts numbers.inspect   # [10, 2, 4, 5, 6]

Array operations:

numbers = [10, 20, 30, 40, 50]
puts numbers[1..3]     # [20, 30, 40]
puts numbers.first     # 10
puts numbers.last      # 50
puts numbers.include?(30)  # true

4.2 Hash

A hash is a collection of key-value pairs, similar to dictionaries in other languages.

student = {
  name: "John",
  age: 20,
  major: "Computer Science"
}

# Accessing and modifying hash
puts student[:name]
student[:age] = 21
student[:gpa] = 3.8

# Iterating over hash
student.each do |key, value|
  puts "#{key}: #{value}"
end

5. Control Flow

Ruby provides several control flow statements to manage program execution.

5.1 if Statements

The if statement evaluates a condition and executes its block if the condition is true.

age = 20
if age >= 18
  puts "Adult"
elsif age >= 13
  puts "Teen"
else
  puts "Child"
end

# One-line if
puts "Adult" if age >= 18

5.2 unless Statements

unless is the opposite of if - executes when the condition is false.

age = 15
unless age >= 18
  puts "Not an adult"
end

# One-line unless
puts "Not an adult" unless age >= 18

5.3 case Statements

case statements provide a clean way to handle multiple conditions.

grade = "B"

case grade
when "A"
  puts "Excellent"
when "B"
  puts "Good"
when "C"
  puts "Average"
else
  puts "Needs improvement"
end

5.4 Loops

Ruby supports various loop constructs.

while loop:

count = 0
while count < 5
  puts count
  count += 1
end

until loop:

count = 0
until count >= 5
  puts count
  count += 1
end

for loop:

for i in 0..4
  puts i
end

each iterator:

(0..4).each do |i|
  puts i
end

# With arrays
fruits = ["apple", "banana", "cherry"]
fruits.each do |fruit|
  puts fruit
end

break and next:

(0..9).each do |i|
  break if i == 5     # Exit loop
  next if i % 2 == 0  # Skip even numbers
  puts i              # Output: 1, 3
end

6. Methods

Methods in Ruby are defined using the def keyword.

Basic Method Definition:

def greet(name)
  "Hello, #{name}!"
end

# Calling the method
message = greet("John")
puts message

Default Parameters:

def greet(name, greeting = "Hello")
  "#{greeting}, #{name}!"
end

puts greet("Alice")          # "Hello, Alice!"
puts greet("Bob", "Hi")      # "Hi, Bob!"

Variable Arguments:

def sum_numbers(*numbers)
  numbers.sum
end

puts sum_numbers(1, 2, 3, 4)  # 10

Keyword Arguments:

def create_person(name:, age:, city: "Unknown")
  { name: name, age: age, city: city }
end

person = create_person(name: "Alice", age: 25)
puts person.inspect

7. Blocks and Procs

Blocks are chunks of code that can be passed to methods.

Using Blocks:

# Using do...end
3.times do
  puts "Hello!"
end

# Using curly braces
3.times { puts "Hello!" }

# Blocks with parameters
(1..3).each do |number|
  puts "Number: #{number}"
end

Yield Keyword:

def run_block
  puts "Before block"
  yield
  puts "After block"
end

run_block { puts "Inside block" }

Procs:

Procs are objects that encapsulate blocks.

square = Proc.new { |x| x * x }
puts square.call(5)  # 25

# Passing procs to methods
def apply_operation(numbers, operation)
  numbers.map { |n| operation.call(n) }
end

numbers = [1, 2, 3, 4]
squares = apply_operation(numbers, square)
puts squares.inspect  # [1, 4, 9, 16]

8. Classes and Objects

Ruby is a pure object-oriented language where everything is an object.

Basic Class Definition:

class Person
  def initialize(name, age)
    @name = name
    @age = age
  end

  def introduce
    "I am #{@name}, #{@age} years old"
  end

  def have_birthday
    @age += 1
    "#{@name} had a birthday, now #{@age} years old"
  end
end

# Creating objects
person1 = Person.new("John", 25)
person2 = Person.new("Jane", 30)

puts person1.introduce
puts person2.have_birthday

Accessor Methods:

class Person
  attr_reader :name    # Read access
  attr_writer :age     # Write access
  attr_accessor :city  # Read and write access

  def initialize(name, age, city)
    @name = name
    @age = age
    @city = city
  end
end

person = Person.new("Alice", 25, "New York")
puts person.name      # "Alice"
person.age = 26       # Set age
person.city = "Boston" # Set city
puts person.city      # "Boston"

Class Methods and Variables:

class Student
  @@student_count = 0  # Class variable

  def initialize(name)
    @name = name
    @@student_count += 1
  end

  def self.student_count  # Class method
    @@student_count
  end
end

student1 = Student.new("John")
student2 = Student.new("Jane")
puts Student.student_count  # 2

Inheritance:

class Animal
  def initialize(name)
    @name = name
  end

  def speak
    "#{@name} makes a sound"
  end
end

class Dog < Animal
  def speak
    "#{@name} barks"
  end
end

class Cat < Animal
  def speak
    "#{@name} meows"
  end
end

dog = Dog.new("Buddy")
cat = Cat.new("Mimi")

puts dog.speak  # "Buddy barks"
puts cat.speak  # "Mimi meows"

9. Modules and Mixins

Modules are used to group related methods and constants, and can be mixed into classes.

Module Definition:

module Speakable
  def speak
    "#{@name} says something"
  end
end

class Person
  include Speakable

  def initialize(name)
    @name = name
  end
end

person = Person.new("Alice")
puts person.speak  # "Alice says something"

Namespacing with Modules:

module Math
  PI = 3.14159

  def self.square(x)
    x * x
  end
end

puts Math::PI        # 3.14159
puts Math.square(5)  # 25

10. Exception Handling

Ruby provides robust exception handling using begin, rescue, ensure, and raise.

Basic Exception Handling:

begin
  result = 10 / 0
rescue ZeroDivisionError => e
  puts "Cannot divide by zero: #{e.message}"
else
  puts "Division successful"
ensure
  puts "This always runs"
end

Raising Exceptions:

def divide(a, b)
  raise "Cannot divide by zero" if b == 0
  a / b
end

begin
  result = divide(10, 0)
rescue => e
  puts "Error: #{e.message}"
end

11. File Operations

Ruby provides simple methods for reading and writing files.

Reading Files:

# Read entire file
content = File.read("example.txt")
puts content

# Read line by line
File.foreach("example.txt") do |line|
  puts line.chomp
end

Writing Files:

# Write to file
File.write("output.txt", "Hello, Ruby!\n")

# Append to file
File.open("output.txt", "a") do |file|
  file.puts "Appending new content."
end

12. Useful Built-in Methods

Ruby comes with many useful built-in methods.

String Methods:

text = "  Ruby Programming  "
puts text.strip        # Remove whitespace
puts text.split(" ")   # Split into array
puts text.gsub("Ruby", "Python")  # Replace

Array Methods:

numbers = [3, 1, 4, 1, 5, 9, 2]
puts numbers.sort.inspect      # [1, 1, 2, 3, 4, 5, 9]
puts numbers.uniq.inspect      # [3, 1, 4, 5, 9, 2]
puts numbers.select { |n| n > 3 }.inspect  # [4, 5, 9]

Hash Methods:

person = { name: "Alice", age: 25, city: "New York" }
puts person.keys.inspect    # [:name, :age, :city]
puts person.values.inspect  # ["Alice", 25, "New York"]
puts person.has_key?(:age)  # true

13. Ruby Gems

RubyGems is Ruby’s package manager for installing and managing libraries.

Installing Gems:

gem install rails

Using Gems in Code:

require 'json'

# Parse JSON
json_string = '{"name": "Alice", "age": 25}'
person = JSON.parse(json_string)
puts person["name"]  # "Alice"

# Generate JSON
person_hash = { name: "Bob", age: 30 }
json_output = JSON.generate(person_hash)
puts json_output  # {"name":"Bob","age":30}

14. Ruby Style Guide

Ruby has a strong community style guide that promotes clean, readable code.

Indentation: Use 2 spaces for indentation.

Naming Conventions:

  • Variables and methods: snake_case
  • Classes and modules: CamelCase
  • Constants: SCREAMING_SNAKE_CASE

Parentheses: Use parentheses for method calls with arguments, omit for method calls without arguments.

Blocks: Use do...end for multi-line blocks, {} for single-line blocks.

Ruby’s elegant syntax and powerful features make it a joy to work with. Its focus on developer happiness and productivity has made it popular for web development, scripting, and automation tasks.