if x > 0
puts "Positive"
elsif x == 0
puts "Zero"
else
puts "Negative"
end
for i in 1..3
puts i
end
3.times { puts "Hi" }
Methods
Method
def add(a, b)
a + b
end
def greet(name = "World")
puts "Hello, #{name}!"
end
Blocks
Block
def repeat(n)
n.times { yield }
end
repeat(3) { puts "Hello" }
[1,2,3].each { |x| puts x }
Procs
Proc
p = Proc.new { |x| puts x }
p.call(5)
[1,2,3].each(&p)
Lambdas
Lambda
l = ->(x) { x * 2 }
puts l.call(3) # 6
Classes
Class
class Person
attr_accessor :name
def initialize(name)
@name = name
end
def greet
puts "Hi, I'm #{@name}"
end
end
p = Person.new("Bob")
p.greet
Objects
Object
p = Person.new("Alice")
p.name = "Eve"
puts p.name
Inheritance
Inheritance
class Animal
def speak
puts "..."
end
end
class Dog < Animal
def speak
puts "Woof"
end
end
Dog.new.speak
Modules
Module
module MathUtils
def self.add(a, b)
a + b
end
end
puts MathUtils.add(5, 3)
Mixins
Mixin
module StringExtensions
def reverse_words
self.split.reverse.join(' ')
end
end
class String
include StringExtensions
end
puts "Hello World".reverse_words
5.times { |i| puts i }
[1,2,3].each_with_index { |v, i| puts "#{i}: #{v}" }
(1..3).step(2) { |n| puts n }
loop do
break
end
File I/O
File I/O
File.open("test.txt", "w") do |f|
f.puts "Hello, World!"
end
File.read("test.txt")
File.delete("test.txt")
Exception Handling
Exception
begin
# Code that might raise an exception
raise "Error!"
rescue StandardError => e
puts "Caught an exception: #{e.message}"
ensure
puts "This will always execute"
end
Regex
Regex
text = "Hello, Ruby!"
match = text.match(/Ruby/)
puts match[0] # Ruby
text.gsub(/Ruby/, "Rails") # Hello, Rails!
text.scan(/[a-z]+/) # ["Hello", "Ruby"]