At the advanced level, Ruby programmers dive deeper into metaprogramming, advanced OOP, concurrency, testing, and optimization. These concepts prepare you for building large-scale, production-ready Ruby applications.
1. Metaprogramming
Metaprogramming allows you to write code that can modify or generate other code at runtime. Ruby provides methods like send, define_method, and reflection.
๐ Example:
class DynamicGreeter
define_method(:greet) do |name|
puts "Hello, #{name}!"
end
end
greeter = DynamicGreeter.new
greeter.greet("Ruby") # "Hello, Ruby!"
Ruby2. Advanced OOP Concepts
Ruby supports inheritance, polymorphism, and encapsulation, which help build scalable applications.
๐ Example:
class Animal
def speak
puts "Some sound"
end
end
class Dog < Animal
def speak
puts "Woof!"
end
end
animal = Animal.new
dog = Dog.new
animal.speak # "Some sound"
dog.speak # "Woof!"
Ruby3. Concurrency and Multithreading
Ruby supports threads and fibers for concurrent programming.
๐ Example with Threads:
threads = []
3.times do |i|
threads << Thread.new do
puts "Thread #{i} is running"
sleep(1)
puts "Thread #{i} is finished"
end
end
threads.each(&:join)
Ruby4. Garbage Collection and Memory Management
Ruby automatically handles memory with its garbage collector, but developers can optimize memory usage with techniques like object re-use and profiling.
๐ Example (Measuring memory):
require 'objspace'
arr = []
1000.times { arr << "memory".dup }
puts ObjectSpace.memsize_of(arr) # Shows memory size of the array
Ruby5. Ruby on Rails Basics
Rails is a popular web framework built on Ruby. It follows the MVC (Model-View-Controller) pattern.
๐ Example (Simple Rails Route):
# In config/routes.rb
Rails.application.routes.draw do
get 'welcome/index'
end
# In app/controllers/welcome_controller.rb
class WelcomeController < ApplicationController
def index
end
end
# In app/views/welcome/index.html.erb
<h1>Hello from Rails!</h1>
Ruby6. Testing in Ruby (RSpec & Minitest)
Writing tests ensures code reliability.
๐ Example with RSpec:
# spec/calculator_spec.rb
require 'rspec'
class Calculator
def add(a, b)
a + b
end
end
RSpec.describe Calculator do
it "adds two numbers" do
calc = Calculator.new
expect(calc.add(2, 3)).to eq(5)
end
end
Ruby7. Performance Optimization
Optimizing Ruby code involves reducing memory usage, avoiding unnecessary loops, and using built-in methods efficiently.
๐ Inefficient vs Optimized Example:
# Inefficient
result = []
[1,2,3,4,5].each { |n| result << n * 2 }
# Optimized
result = [1,2,3,4,5].map { |n| n * 2 }
puts result.inspect # [2, 4, 6, 8, 10]
Rubyโ With these advanced concepts, you are ready to build high-performance Ruby applications. Whether you aim to master Rails web apps, delve into metaprogramming, or optimize for large-scale systems, Ruby provides powerful tools to take your skills to the next level.
