Learn RUBY with Real Code Examples
Updated Nov 17, 2025
Code Sample Descriptions
Ruby Blocks and Iterators
class Calculator
def initialize
@history = []
end
def add(a, b)
result = a + b
@history << "#{a} + #{b} = #{result}"
result
end
def multiply(a, b)
result = a * b
@history << "#{a} * #{b} = #{result}"
result
end
def history
@history.each_with_index do |operation, index|
puts "#{index + 1}. #{operation}"
end
end
end
# Array operations with blocks
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = numbers.select { |n| n.even? }
squares = numbers.map { |n| n ** 2 }
sum = numbers.reduce(0) { |acc, n| acc + n }
puts "Even numbers: #{even_numbers}"
puts "Squares: #{squares}"
puts "Sum: #{sum}"
# Calculator usage
calc = Calculator.new
calc.add(5, 3)
calc.multiply(4, 6)
calc.history
Demonstrates Ruby's elegant syntax with blocks, classes, and enumerable methods.
Ruby Classes and Inheritance
class Animal
def speak
"Generic animal sound"
end
end
class Dog < Animal
def speak
"Woof!"
end
end
class Cat < Animal
def speak
"Meow!"
end
end
animals = [Dog.new, Cat.new, Animal.new]
animals.each do |animal|
puts animal.speak
end
Shows how Ruby supports inheritance and method overriding in object-oriented programming.
Ruby Modules and Mixins
module Greetable
def greet(name)
"Hello, #{name}!"
end
end
class Person
include Greetable
end
class Robot
include Greetable
end
p1 = Person.new
r1 = Robot.new
puts p1.greet("Alice")
puts r1.greet("R2D2")
Demonstrates Ruby's use of modules for reusable functionality and multiple inheritance.
Ruby File Handling
File.open("example.txt", "w") do |file|
file.puts "This is a sample text file."
file.puts "Written with Ruby!"
end
puts "File written successfully."
puts "Reading file contents:"
File.readlines("example.txt").each_with_index do |line, index|
puts "#{index + 1}: #{line.strip}"
end
Shows how to read and write files in Ruby safely using blocks.
Ruby Exception Handling
def divide(a, b)
begin
result = a / b
puts "Result: #{result}"
rescue ZeroDivisionError => e
puts "Error: Division by zero!"
ensure
puts "Division attempt finished."
end
end
divide(10, 2)
divide(5, 0)
Demonstrates the use of begin-rescue-ensure for robust error handling in Ruby.
Ruby Hashes and Symbols
person = {
name: "Alice",
age: 25,
city: "Kathmandu"
}
person.each do |key, value|
puts "#{key.capitalize}: #{value}"
end
puts "Name in uppercase: #{person[:name].upcase}"
Shows how to create and iterate through hashes using Ruby's symbol keys.
Ruby Regular Expressions
text = "Contact us at support@example.com or visit our website."
email_pattern = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z]{2,}\b/i
if text.match?(email_pattern)
puts "Email found!"
puts text.scan(email_pattern)
else
puts "No email found."
end
Explores Ruby's powerful regex features for pattern matching and text parsing.
Ruby Enumerables and Map
numbers = (1..10).to_a
evens = numbers.select { |n| n.even? }
squares = numbers.map { |n| n ** 2 }
sum = numbers.reduce(:+)
puts "Even numbers: #{evens}"
puts "Squares: #{squares}"
puts "Sum: #{sum}"
Demonstrates functional programming style using map, select, and reduce on Ruby collections.
Ruby JSON Parsing
require 'json'
data = {
name: "Saurav",
age: 22,
skills: ["Ruby", "JavaScript", "Flutter"]
}
json_str = JSON.pretty_generate(data)
puts "JSON Output:"
puts json_str
parsed = JSON.parse(json_str)
puts "Parsed Name: #{parsed['name']}"
Shows how to work with JSON data using Ruby's built-in JSON module.
Ruby Time and Date Formatting
require 'date'
now = Time.now
puts "Current time: #{now}"
puts "Formatted: #{now.strftime("%A, %d %B %Y %I:%M %p")}"
birthday = Date.new(2000, 5, 12)
age = ((Date.today - birthday).to_i / 365.25).floor
puts "Age based on DOB #{birthday}: #{age} years"
Illustrates Ruby's Time and Date manipulation for formatting and calculation.