Designed for programmer happiness โ Ruby reads almost like English, and it's the language behind Ruby on Rails, one of the most influential web frameworks ever built. Copy-paste examples plus live Run/Submit exercises.
puts "Hello, world!"
age = 25
name = "Sam"
price = 19.99
PI = 3.14159 # CAPS by convention means "don't reassign this"
age = 20
if age >= 18
puts "Adult"
elsif age >= 13
puts "Teen"
else
puts "Child"
end
end.5.times do |i|
puts i
end
n = 3
while n > 0
puts n
n -= 1
end
nums = [10, 20, 30]
nums << 40 # append with <<
puts nums[0] # 10
puts nums.length # 4
ages = { "Sam" => 25, "Ana" => 30 }
puts ages["Sam"] # 25
ages["Lee"] = 40
Ruby's signature feature โ chunks of code you pass into methods, used everywhere instead of manual loops.
nums = [1, 2, 3, 4]
doubled = nums.map { |n| n * 2 }
evens = nums.select { |n| n.even? }
total = nums.reduce(0) { |sum, n| sum + n }
class Dog
def initialize(name, age)
@name = name
@age = age
end
def bark
puts "#{@name} says woof!"
end
end
# d = Dog.new("Rex", 3); d.bark
Full runnable scripts, run in a real Ruby sandbox โ same workspace as the other cheat sheets.
nums = [4, 8, 15, 16, 23, 42]
puts nums.reduce(0) { |sum, n| sum + n }
def reverse_str(s)
s.reverse
end
puts reverse_str("ruby")
(1..15).each do |i|
if i % 15 == 0
puts "FizzBuzz"
elsif i % 3 == 0
puts "Fizz"
elsif i % 5 == 0
puts "Buzz"
else
puts i
end
end
text = "the cat sat on the mat the cat ran"
counts = Hash.new(0)
text.split.each { |word| counts[word] += 1 }
counts.each { |word, n| puts "#{word}: #{n}" }