Ruby Cheat Sheet
Quick reference from FreeCodingCourses.com
Variables and types
name = "Ada"- no declaration keyword needed.
count = 5- Integer.
price = 9.99- Float.
ok = true- true or false, lowercase.
nada = nil- the null value in Ruby.
:active- a Symbol, an immutable name.
5.class- everything is an object; ask its class.
Strings
"Hi #{name}"- double quotes interpolate with #{}.
'Hi #{name}'- single quotes do not interpolate.
s.upcase- uppercase (downcase for lower).
s.strip- trim whitespace from both ends.
s.split(",")- split into an array.
arr.join(", ")- join an array into a string.
s.gsub("a", "b")- replace every occurrence.
s.include?("ab")- true if the substring is present.
Arrays
nums = [1, 2, 3]- ordered and mutable.
nums << 4- push onto the end (same as push).
nums.first- first item (last for the last).
nums.pop- remove from the end (shift for the front).
nums.length- item count.
nums.include?(2)- membership test.
nums.sort- a new sorted array (reverse to flip).
nums.uniq- drop duplicate values.
Hashes
user = { name: "Ada", age: 36 }- symbol keys, shorthand syntax.
user[:name]- read a value by key.
user[:email] = "[email protected]"- add or update a key.
user.fetch(:email, "n/a")- read with a default fallback.
user.key?(:name)- true if the key exists.
user.keys- all keys (values for the values).
user.each { |k, v| puts "#{k}=#{v}" }- iterate the pairs.
Blocks and iterators
nums.each { |n| puts n }- run a block per item.
nums.map { |n| n * 2 }- transform into a new array.
nums.select { |n| n > 1 }- keep items that pass.
nums.reject { |n| n > 1 }- drop items that pass.
nums.reduce(0) { |sum, n| sum + n }- fold to one value.
nums.each_with_index { |n, i| }- item and index together.
3.times { |i| puts i }- repeat a block n times.
Control flow
if x > 0 elsif else end- end closes the block.
puts "hi" if ok- trailing if, reads left to right.
unless ok end- runs when the condition is false.
case s when 200 then "ok" else "?" end- case and when.
while cond end- loop until the condition is false.
x || "fallback"- default when x is nil or false.
user&.name- safe navigation: nil if user is nil.
Methods and classes
def add(a, b) a + b end- last expression is returned.
def greet(name = "friend")- default argument.
def total(*nums)- splat: any number of args.
class User end- define a class.
def initialize(name) @name = name end- constructor; @ is an instance var.
attr_accessor :name- generate a getter and setter.
User.new("Ada")- create an instance.
Unlock the full Ruby cheat sheet
You're seeing 2 of 7 sections. Drop your email to open the rest plus the gotchas, and save the whole thing as a printable PDF.
No spam, unsubscribe anytime. See our privacy policy.