Introduction
Ruby is an elegant, expressive programming language that prioritizes developer happiness. In this guide, we’ll learn the fundamentals of Ruby that you’ll need to start building Rails applications.
Getting Started with Ruby
What is Ruby?
Ruby is a dynamic, object-oriented programming language created by Yukihiro "Matz" Matsumoto. It’s designed to be:
-
Intuitive and natural to read
-
Fun and productive to write
-
Powerful and flexible
Interactive Ruby (IRB)
Open your terminal and type irb
to start an interactive Ruby session:
$ irb
irb(main):001:0> 2 + 2
=> 4
irb(main):002:0> "hello".upcase
=> "HELLO"
Tip
|
IRB is great for experimenting with Ruby code and testing quick ideas. |
Ruby Fundamentals
Variables and Data Types
Variables in Ruby don’t need explicit declaration:
# Numbers
age = 25 # Integer
price = 19.99 # Float
# Strings
name = "Ruby"
greeting = 'Hello'
# Booleans
is_active = true
has_errors = false
# Arrays
numbers = [1, 2, 3, 4, 5]
names = ["Alice", "Bob", "Charlie"]
# Hashes
person = {
name: "John",
age: 30,
city: "Portland"
}
String Manipulation
Strings in Ruby are incredibly flexible:
# String concatenation
first_name = "Ruby"
last_name = "Developer"
full_name = first_name + " " + last_name
=> "Ruby Developer"
# String interpolation
greeting = "Hello, #{first_name}!"
=> "Hello, Ruby!"
# Common string methods
name = "ruby"
name.upcase # => "RUBY"
name.capitalize # => "Ruby"
name.reverse # => "ybur"
name.length # => 4
Working with Arrays
Arrays are ordered collections of objects:
# Creating arrays
numbers = [1, 2, 3, 4, 5]
fruits = %w[apple banana orange] # => ["apple", "banana", "orange"]
# Common array operations
numbers.first # => 1
numbers.last # => 5
numbers.length # => 5
numbers.include?(3) # => true
numbers << 6 # => [1, 2, 3, 4, 5, 6]
# Array iteration
fruits.each do |fruit|
puts "I love #{fruit}!"
end
# Array transformation
doubled = numbers.map { |n| n * 2 }
=> [2, 4, 6, 8, 10]
# Array filtering
even_numbers = numbers.select { |n| n.even? }
=> [2, 4, 6]
Working with Hashes
Hashes are collections of key-value pairs:
# Creating hashes
person = {
name: "John",
age: 30,
city: "Portland"
}
# Accessing hash values
person[:name] # => "John"
person.fetch(:age) # => 30
# Adding/updating values
person[:email] = "john@example.com"
person[:age] = 31
# Iterating over hashes
person.each do |key, value|
puts "#{key}: #{value}"
end
Control Flow
Conditionals
# If statements
if age >= 18
puts "You're an adult"
elsif age >= 13
puts "You're a teenager"
else
puts "You're a child"
end
# Unless statement (opposite of if)
unless is_admin
puts "Access denied"
end
# Case statement
case status
when "pending"
process_order
when "shipped"
send_notification
else
log_error
end
Loops and Iteration
# While loop
counter = 0
while counter < 5
puts counter
counter += 1
end
# Each loop (preferred)
5.times do |i|
puts i
end
# Range iteration
(1..5).each do |n|
puts n
end
Methods
Methods are reusable blocks of code:
# Basic method
def greet(name)
"Hello, #{name}!"
end
# Method with default parameter
def calculate_total(price, tax_rate = 0.1)
price + (price * tax_rate)
end
# Method with multiple parameters
def create_user(name:, email:, age: nil)
puts "Creating user: #{name} (#{email})"
end
# Calling methods
greeting = greet("Ruby")
total = calculate_total(100)
create_user(name: "John", email: "john@example.com")
Classes and Objects
Creating a Class
class Person
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
def introduce
"Hi, I'm #{name} and I'm #{age} years old."
end
def birthday
@age += 1
end
end
# Using the class
person = Person.new("Ruby", 25)
puts person.introduce
person.birthday
puts person.age # => 26
Practical Examples
Building a Todo List
class TodoList
def initialize
@tasks = []
end
def add_task(description)
@tasks << {
id: next_id,
description: description,
completed: false
}
end
def complete_task(id)
task = find_task(id)
task[:completed] = true if task
end
def list_tasks
@tasks.each do |task|
status = task[:completed] ? "✓" : " "
puts "[#{status}] #{task[:description]}"
end
end
private
def next_id
@tasks.length + 1
end
def find_task(id)
@tasks.find { |task| task[:id] == id }
end
end
# Using the TodoList
list = TodoList.new
list.add_task("Learn Ruby")
list.add_task("Build Rails App")
list.complete_task(1)
list.list_tasks
Best Practices
Ruby Style Guide
-
Use 2 spaces for indentation
-
Use snake_case for methods and variables
-
Use CamelCase for classes and modules
-
End files with a newline
-
Avoid unnecessary comments
-
Keep methods small and focused
Common Conventions
-
Prefer
each
overfor
loops -
Use string interpolation over concatenation
-
Use symbols instead of strings for hash keys
-
Follow the principle of least surprise
Next Steps
Now that you understand Ruby basics, you’re ready to:
-
Explore more advanced Ruby concepts
-
Start learning Ruby on Rails
-
Build practice projects
-
Join Ruby communities
Additional Resources
Tip
|
Practice these concepts in IRB as you learn them. The best way to learn Ruby is by writing Ruby! |
Warning
|
Remember that Ruby is very flexible, but with great power comes great responsibility. Always follow Ruby conventions and best practices. |