Complete reference for Ruby built-in classes and modules — String, Array, Hash, File, Enumerable and more with copy-paste examples.
Part of The Direct Path to Linux Ubuntu — free for all.
Save as .rb file and run with ruby script.rb.
Ruby basics — string interpolation, blocks, ranges.
#!/usr/bin/env ruby
def greet(name)
"Hello, #{name.capitalize}! Ruby #{RUBY_VERSION} on #{RUBY_PLATFORM}"
end
puts greet("world")
puts greet("mywebuniversity")
# Blocks and ranges
(1..5).each { |i| print "#{i}^2=#{i**2} " }; puts
# One-liner array processing
puts (1..10).select(&:even?).map { |n| n * n }.inspect
# Everything is an expression
result = if Time.now.hour < 12 then "Good morning" else "Good afternoon" end
puts result
# ruby hello.rbRuby classes, mixins, attr_accessor, and comparable.
module Describable
def describe = "#{self.class.name}: #{self}"
end
class Animal
include Describable
include Comparable
attr_accessor :name, :age
def initialize(name, age) = (@name, @age = name, age)
def <=>(other) = @age <=> other.age
def to_s = "#{@name}(#{@age})"
end
class Dog < Animal
def speak = "#{@name} says: Woof!"
end
class Cat < Animal
def speak = "#{@name} says: Meow!"
end
animals = [Dog.new("Rex",3), Cat.new("Luna",7), Dog.new("Max",1), Cat.new("Cleo",5)]
puts animals.sort.map(&:to_s).inspect
puts animals.max.describe
animals.each(&:speak).each { |a| puts a.speak }
# ruby oop_demo.rbRuby's first-class callables and functional patterns.
# Proc vs Lambda
square = proc { |x| x * x }
cube = lambda { |x| x ** 3 }
double = ->(x) { x * 2 }
[1,2,3,4,5].each { |n| puts "#{n}: sq=#{square.(n)} cu=#{cube.(n)} dbl=#{double.(n)}" }
# Function composition (Ruby 2.6+)
triple = ->(x) { x * 3 }
add_one = ->(x) { x + 1 }
pipeline = triple >> add_one
puts (1..5).map(&pipeline).inspect
# yield and block_given?
def repeat(n)
n.times { yield } if block_given?
end
repeat(3) { print "Ruby! " }; puts
# Memoization with Hash default
fib = Hash.new { |h,n| h[n] = n < 2 ? n : h[n-1] + h[n-2] }
puts (0..10).map { |n| fib[n] }.inspect
# ruby blocks_demo.rbParse a CSV file and extract data with regex.
require "csv"
File.write("students.csv", <<~CSV)
Name,Subject,Score,Email
Alice,Math,95,alice@example.com
Bob,Science,87,bob@example.com
Carol,Math,92,carol@example.com
Dave,Science,78,dave@example.com
Eve,Math,98,eve@example.com
CSV
students = CSV.foreach("students.csv", headers: true).map do |row|
{ name: row["Name"], subject: row["Subject"],
score: row["Score"].to_i, email: row["Email"] }
end
students.group_by { |s| s[:subject] }.each do |subj, group|
avg = group.sum { |s| s[:score] }.to_f / group.size
puts "#{subj}: avg=#{avg.round(1)} top=#{group.max_by{|s|s[:score]}[:name]}"
end
emails = File.read("students.csv").scan(/[\w.+-]+@[\w-]+\.[\w.]+/)
puts "Emails: #{emails.inspect}"
puts "Domains: #{emails.map { |e| e.split("@").last }.uniq.inspect}"
File.delete("students.csv")
# ruby csv_demo.rbRuby threads, mutex synchronization, and fiber coroutines.
# Threads with Mutex
counter = 0
mutex = Mutex.new
threads = 10.times.map do |i|
Thread.new do
100.times { mutex.synchronize { counter += 1 } }
end
end
threads.each(&:join)
puts "Counter: #{counter} (expected 1000)"
# Queue (producer-consumer)
require "thread"
queue = Queue.new
producer = Thread.new { 5.times { |i| queue << "item-#{i}"; sleep 0.01 }; queue << :done }
items = []
consumer = Thread.new { loop { (v = queue.pop) == :done ? break : items << v } }
[producer, consumer].each(&:join)
puts "Consumed: #{items.inspect}"
# Fiber (coroutine)
fib = Fiber.new do
a, b = 0, 1
loop { Fiber.yield a; a, b = b, a + b }
end
puts (10.times.map { fib.resume }).inspect
# ruby threads_demo.rb