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.
Gotchas worth knowing
- •Methods return the value of their last expression, so an explicit return is usually unneeded. def double(n); n * 2; end already returns the doubled number.
- •A method ending in ? returns a boolean, like nil? or include?. A method ending in ! usually mutates the receiver or raises, like sort! versus sort. These are conventions, but the whole ecosystem follows them.
- •Symbols like :name are not strings. They are immutable and reused, which makes them the right choice for hash keys and option flags. "name" and :name are different objects.
- •Use << to append to an array or build up a string; it is the common idiom and reads cleanly. nums << 4 does the same thing as nums.push(4).
- •Prefer each, map, and select over a manual for loop. Ruby developers almost never write for; the block iterators are clearer and are what everyone expects to read.