Ruby 3 cheatsheet
Ruby 3: Basics
8 common Ruby 3 tasks.
Print and interpolate
Print a line, inserting expressions with #{}. Double quotes interpolate; single quotes don't.
name = "Ada"
puts "Hello, #{name}! 2 + 2 = #{2 + 2}"
Use hashes and symbols
Hashes map keys to values. Symbols like :name are cheap, immutable names.
user = { name: "Ada", age: 36 }
puts user[:name]
user[:email] = "[email protected]"
Transform arrays
Arrays have rich methods, and most take blocks.
numbers = [1, 2, 3, 4, 5]
squares = numbers.map { |n| n * n }
evens = numbers.select(&:even?)
total = numbers.sum
Loop with an index
Iterate with each_with_index, or each_with_object to build a result.
%w[a b c].each_with_index { |letter, i| puts "#{i}: #{letter}" }
Branch
Use if, unless and the ternary operator. Only nil and false are falsy.
puts n > 0 ? "positive" : "not positive" if n
puts "empty" if list.empty?
Define a method with keyword arguments
Keyword arguments make calls self-documenting. The last expression is returned.
def greet(name:, greeting: "Hello")
"#{greeting}, #{name}!"
end
puts greet(name: "Ada")
Handle nil safely
&. calls a method only if the receiver is not nil.
city = user&.dig(:address, :city)
Common string methods
Strings have many helpers.
" Hello World ".strip.downcase.split(" ").map(&:capitalize).join("-")