iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Cheatsheet

A one-page Ruby reference covering the syntax + idioms you reach for daily.

Ruby in one page

EXAMPLE
# ===== Variables + types =====
name = 'alice'             # local
@name = 'alice'            # instance
@@name = 'alice'           # class (avoid)
$name = 'alice'            # global (avoid)
NAME = 'alice'             # constant

# Strings
'single quote'             # literal
"double quote with #{1+1}"   # interpolation
%w[a b c]                  # array of strings: ['a','b','c']
%i[a b c]                  # array of symbols: [:a,:b,:c]

# Numbers
1_000_000                  # underscores for readability
0xff                       # hex
3.14                       # float
Rational(1, 3)             # exact fractions
BigDecimal('1.23')         # arbitrary precision

# ===== Collections =====
[1, 2, 3].map { |n| n * 2 }
[1, 2, 3].each { |n| puts n }
[1, 2, 3].select(&:even?)
[1, 2, 3].reduce(0) { |s, n| s + n }
[1, 2, 3].reduce(:+)             # sum via Symbol#to_proc
[1, 2, 3].group_by(&:odd?)
[1, 2, 3].each_with_index { |n, i| puts "#{i}: #{n}" }

# Hashes
h = { name: 'alice', age: 30 }
h[:name]
h.fetch(:role, 'guest')          # default if missing
h.each { |k, v| puts "#{k}=#{v}" }
h.merge(role: 'admin')
h.transform_values { |v| v.to_s }
h.slice(:name)

# Ranges
(1..10).to_a
(1...10).to_a                    # exclusive
('a'..'e').to_a

# ===== Control flow =====
puts 'hi' if x > 0
puts 'lo' unless x > 0
x = 1 == 2 ? 'no' : 'yes'

case status
when 'new'      then 'open'
when 'paid'     then 'open'
when 'shipped'  then 'done'
else                 'unknown'
end

5.times { |i| puts i }
1.upto(5)   { |i| puts i }
[1,2,3].each { |i| puts i }

while x > 0 do x -= 1 end
loop do break if done end

# ===== Methods + blocks =====
def greet(name = 'world', greeting: 'Hello')
  "#{greeting}, #{name}!"
end

greet
greet('alice')
greet('alice', greeting: 'Hi')

# Block, proc, lambda
[1,2,3].each { |n| puts n }              # block
square = proc  { |n| n * n }              # proc (no arity check)
square = lambda { |n| n * n }             # lambda (strict arity, return-local)
square = ->(n) { n * n }                  # shortcut lambda

# Splat + double splat
def take_args(*args, **kwargs); end

# ===== Classes =====
class Customer
  attr_accessor :name, :email             # auto getters + setters
  attr_reader   :id                        # getter only

  def initialize(name:, email:)
    @id = SecureRandom.uuid
    @name = name
    @email = email
  end

  def to_s = "#{@name} <#{@email}>"
end

class Vip < Customer                       # inheritance
  def to_s = "⭐ #{super}"
end

# ===== Modules (mixins) =====
module Auditable
  def log_event(event)
    Logger.info("#{self.class}: #{event}")
  end
end

class Order
  include Auditable
end

# ===== Exception handling =====
begin
  risky_thing
rescue ArgumentError => e
  puts "bad args: #{e.message}"
rescue => e                                # catches StandardError, NOT Exception
  puts "other: #{e.message}"
ensure
  cleanup
end

# Method-level rescue
def safe_thing
  risky_thing
rescue StandardError => e
  nil
end

# ===== Files + IO =====
File.read('path')
File.write('path', 'hello')
File.open('path', 'r') { |f| f.each_line { |l| puts l } }   # auto-close

# ===== Tooling =====
ruby script.rb
bundle init        # create a Gemfile
bundle add nokogiri
bundle exec rspec
gem install bundler
rubocop --auto-correct
rubocop -A

# ===== Patterns to internalise =====
# - Use blocks; they are Ruby's superpower
# - Hash#fetch + default over h[:key] || 'x'
# - Methods like 'each_with_object' instead of manual accumulators
# - Modules for cross-cutting concerns
# - Implicit return; explicit return is for early exits
# - Symbols (:name) for hash keys and constants

# ===== Pitfalls =====
# - rescue with no class -> catches StandardError only
# - rescue Exception -> swallows SystemExit + Interrupt
# - Mutating a default argument value (use freeze + dup)
# - Strings: 'single' is literal; "double" interpolates
# - .freeze on constants you do not want mutated

Why it matters

Ruby rewards blocks, fetch + default, and tiny mixin modules for cross-cutting concerns. Once those three patterns feel natural, idiomatic Ruby falls out — and the code reads close to English without losing the power of the language.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
ruby | irb | bundle | gem | rake | rails | rspec
Try it Yourself »

Discussion

Loading…