๐Ÿ’Ž

Ruby Cheat Sheet

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.

Jump to: Your first programVariablesif / else LoopsArrays & hashesBlocksClasses ๐Ÿš€ Practice problems

Your first program

puts "Hello, world!"
๐Ÿ“ No semicolons, no main function โ€” Ruby files just run top to bottom.

Variables

age = 25
name = "Sam"
price = 19.99
PI = 3.14159   # CAPS by convention means "don't reassign this"

if / else

age = 20
if age >= 18
  puts "Adult"
elsif age >= 13
  puts "Teen"
else
  puts "Child"
end
๐Ÿ“ No parentheses or braces needed โ€” blocks are closed with end.

Loops

5.times do |i|
  puts i
end

n = 3
while n > 0
  puts n
  n -= 1
end

Arrays & hashes

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

Blocks

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 }

Classes

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

๐Ÿš€ Practice problems

Full runnable scripts, run in a real Ruby sandbox โ€” same workspace as the other cheat sheets.

Sum an array EASY

nums = [4, 8, 15, 16, 23, 42]
puts nums.reduce(0) { |sum, n| sum + n }

Reverse a string MEDIUM

def reverse_str(s)
  s.reverse
end

puts reverse_str("ruby")

FizzBuzz MEDIUM

(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

Word frequency with a hash HARD

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}" }