Once you’ve learned the basics of Ruby, it’s time to explore more advanced features. At this stage, you’ll learn how to organize your code, handle errors, and work with collections and objects.
1. Arrays and Hashes
Arrays store ordered collections of values, while Hashes store key–value pairs.
👉 Example with Arrays:
numbers = [1, 2, 3, 4, 5]
puts numbers[0] # 1
numbers << 6 # Add element
puts numbers.inspect # [1, 2, 3, 4, 5, 6]
Ruby👉 Example with Hashes:
person = { name: "Alice", age: 25, city: "London" }
puts person[:name] # Alice
person[:age] = 26 # Update value
puts person.inspect # {:name=>"Alice", :age=>26, :city=>"London"}
Ruby2. String and Array Methods
Ruby offers many built-in methods to manipulate strings and arrays.
👉 Example:
text = "ruby programming"
puts text.upcase # "RUBY PROGRAMMING"
puts text.capitalize # "Ruby programming"
puts text.reverse # "gnimmargorp ybur"
arr = [5, 2, 8, 1]
puts arr.sort.inspect # [1, 2, 5, 8]
puts arr.include?(2) # true
Ruby3. Classes and Objects (OOP Basics)
Ruby is an object-oriented language. You can define classes and create objects from them.
👉 Example:
class Car
attr_accessor :brand, :model
def initialize(brand, model)
@brand = brand
@model = model
end
def drive
puts "Driving a #{@brand} #{@model}."
end
end
car = Car.new("Toyota", "Corolla")
car.drive
Ruby4. Modules and Mixins
Modules help you organize reusable code. They can also be used as mixins to add functionality to classes.
👉 Example:
module Greetings
def say_hello(name)
puts "Hello, #{name}!"
end
end
class Person
include Greetings
end
p = Person.new
p.say_hello("Alice") # "Hello, Alice!"
Ruby5. Error Handling
You can handle errors gracefully in Ruby using begin, rescue, and ensure.
👉 Example:
begin
result = 10 / 0
rescue ZeroDivisionError
puts "You cannot divide by zero!"
ensure
puts "This code always runs."
end
Ruby6. File Handling
Ruby allows reading from and writing to files.
👉 Example:
# Writing to a file
File.open("example.txt", "w") do |file|
file.puts "Hello, Ruby File!"
end
# Reading from a file
File.open("example.txt", "r") do |file|
puts file.read
end
Ruby7. Blocks, Procs, and Lambdas
Ruby supports functional programming concepts like blocks, procs, and lambdas.
👉 Block Example:
[1, 2, 3].each do |num|
puts num * 2
end
Ruby👉 Proc Example:
my_proc = Proc.new { |x| puts x * 3 }
my_proc.call(5) # 15
Ruby👉 Lambda Example:
my_lambda = ->(x) { puts x * 4 }
my_lambda.call(5) # 20
Ruby✅ By mastering these concepts, you’ll be able to write more structured and reusable Ruby code. The next step is Advanced Level, where you’ll explore metaprogramming, concurrency, and Ruby on Rails basics.
