Ruby Programming

Ruby is an elegant, object-oriented language designed for productivity and fun. Powering Rails and used for web development, scripting, and more. Learn Ruby from the ground up with our comprehensive guide.

Why Learn Ruby?

  • Beautiful, readable syntax that's a joy to work with
  • Power behind Ruby on Rails framework
  • Strong object-oriented principles
  • Great for rapid prototyping and development
  • Vibrant, welcoming community

Getting Started with Ruby

Ruby is a dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.

Installation

Ruby is easy to install on all major platforms:

Windows

  1. Download RubyInstaller from rubyinstaller.org
  2. Run the installer
  3. Check "Add Ruby executables to your PATH"
  4. Click "Install"

macOS/Linux

Use a version manager like rbenv or RVM:

# Using rbenv
$ rbenv install 3.2.2
$ rbenv global 3.2.2

First Program

Create a file named hello.rb with this content:

# A simple Ruby program
puts "Hello, World!"

Run it from your terminal:

$ ruby hello.rb

Ruby Basics

Variables

# Variables don't need type declarations
name = "Alice" # String
age = 30 # Integer
height = 5.9 # Float
is_student = true # Boolean

Basic Operations

# Arithmetic operations
x = 10 + 5 # Addition
y = 10 * 5 # Multiplication

# String operations
greeting = "Hello" + " " + "World"
# String interpolation
message = "My name is #{name}"

Ruby Topics

Comprehensive coverage of Ruby programming concepts from beginner to advanced levels

Variables & Data Types

Learn about Ruby's dynamic typing system and various data types including strings, numbers, arrays, hashes, symbols, and more.

# Example of different data types
name = "Alice" # String
age = 25 # Integer
prices = [10.5, 20.3, 15.0] # Array

Control Flow

Master if-else statements, loops (for, while), and control flow tools to make decisions in your programs.

# If-else example
if age >= 18
  puts "Adult"
else
  puts "Minor"
end

Methods

Learn to define and use methods, work with parameters, return values, and understand scope in Ruby.

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

# Method call
message = greet("Alice")

Arrays & Hashes

Work with Ruby's powerful built-in data structures for storing and organizing data.

# Array and hash examples
fruits = ["apple", "banana", "cherry"]
person = {name: "Alice", age: 25}

# Accessing elements
first_fruit = fruits[0]
person_age = person[:age]

Loops & Iteration

Master each, for, while loops, and iteration techniques in Ruby.

# Each loop example
fruits.each do |fruit|
  puts fruit
end

# Map operation
squares = (1..10).map { |x| x**2 }

File Handling

Learn to read from and write to files, work with different file formats, and manage file operations.

# Writing to a file
File.open("file.txt", "w") do |file|
  file.write("Hello, World!")
end

# Reading from a file
content = File.read("file.txt")

Error Handling

Understand Ruby's exception handling mechanism using begin-rescue blocks to write robust code.

# Begin-rescue example
begin
  result = 10 / 0
rescue ZeroDivisionError => e
  puts "Cannot divide by zero!"
end

Modules & Gems

Organize your code into modules and packages, and learn to use Ruby gems.

# Requiring modules
require 'json'
require 'date'

# Using Ruby gems
require 'nokogiri'

Object-Oriented Programming

Learn classes, objects, inheritance, polymorphism, and other OOP concepts in Ruby.

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

# Creating an object
person = Person.new("Alice", 25)

Working with Gems

Explore popular Ruby gems like Nokogiri, ActiveRecord, and Sinatra for web development.

# Using the HTTParty gem
require 'httparty'

response = HTTParty.get('https://api.example.com')
puts response.body

Metaprogramming

Understand Ruby's powerful metaprogramming capabilities to write dynamic code.

# Metaprogramming example
class Person
  def self.add_method(name)
    define_method(name) { puts "Method #{name} called" }
  end
end

Person.add_method(:greet)
Person.new.greet

Blocks & Procs

Learn about Ruby blocks, procs, and lambdas for powerful functional programming.

# Block example
[1, 2, 3].each do |num|
  puts num * 2
end

# Proc example
square = Proc.new { |x| x**2 }
puts square.call(4)

Mixins

Understand Ruby modules as mixins for multiple inheritance-like behavior.

# Module as mixin
module Loggable
  def log(message)
    puts "[LOG] #{message}"
  end
end

class Service
  include Loggable
end

Service.new.log("Starting service")

Ruby on Rails

Introduction to Ruby on Rails, the popular web application framework.

# Rails controller example
class PostsController < ApplicationController
  def index
    @posts = Post.all
  end
end

Testing with RSpec

Learn to write tests for your Ruby code using the RSpec framework.

# RSpec example
require 'rspec'

def add(a, b)
  a + b
end

RSpec.describe 'add' do
  it 'adds two numbers' do
    expect(add(2, 3)).to eq(5)
  end
end

What Can You Build with Ruby?

Ruby's elegance and expressiveness make it suitable for diverse applications

Web Development

Build powerful web applications using frameworks like:

  • Ruby on Rails (Full-stack framework)
  • Sinatra (Microframework)
  • Hanami (Modern framework)
# Simple Sinatra app
require 'sinatra'

get '/' do
  "Hello, World!"
end

API Development

Build robust APIs with Ruby tools:

  • Rails API mode
  • Grape (API framework)
  • Roda (Routing toolkit)
# Simple Grape API
class API < Grape::API
  version 'v1', using: :path
  format :json

  resource :users do
    get do
      User.all
    end
  end
end

DevOps & Automation

Powerful tools for infrastructure and automation:

  • Chef (Infrastructure as code)
  • Capistrano (Deployment)
  • Rake (Task automation)
# Simple Rake task
require 'rake'

task :greet do
  puts "Hello from Rake!"
end

Scripting & Tools

Ruby excels at scripting and CLI tools:

  • File operations
  • Web scraping (Nokogiri)
  • CLI tools (Thor, GLI)
# File renaming script
Dir.glob('*.txt').each do |file|
  File.rename(file, file.gsub('.txt', '.md'))
end

Testing

Ruby has excellent testing frameworks:

  • RSpec (BDD framework)
  • Minitest (Built-in)
  • Cucumber (Acceptance testing)
# Simple RSpec test
describe 'Calculator' do
  it 'adds two numbers' do
    expect(1 + 1).to eq(2)
  end
end

Desktop Applications

Build cross-platform desktop apps with:

  • Shoes (Simple GUI)
  • GTK (Ruby bindings)
  • FXRuby (FOX toolkit)
# Simple Shoes app
Shoes.app do
  button "Click me" do
    alert "Hello!"
  end
end

Ruby Learning Path

A structured approach to mastering Ruby programming

1 Beginner Level

  • Ruby Syntax and Basics

    Variables, data types, operators, and basic I/O

  • Control Flow

    Conditionals, loops, and exception handling

  • Methods and Blocks

    Defining methods, working with blocks

  • Working with Files

    Reading and writing files

2 Intermediate Level

  • Object-Oriented Programming

    Classes, objects, inheritance, and modules

  • Collections

    Arrays, hashes, sets, and enumerable methods

  • Working with APIs

    HTTP requests, REST APIs, JSON handling

  • Database Interaction

    ActiveRecord, SQLite, PostgreSQL

3 Advanced Level

  • Metaprogramming

    method_missing, define_method, eval

  • Concurrency

    Threads, fibers, and parallel processing

  • DSLs

    Domain Specific Languages in Ruby

  • Performance Optimization

    Benchmarking, profiling, and optimization

Ready to Master Ruby?

Join our Ruby Mastery course and get access to interactive exercises, real-world projects, and expert support to accelerate your learning.