Ruby Cheatsheet
Collections
Use this Ruby reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Arrays
arr = ["a", "b", "c"] arr[0] # "a" arr[-1] # "c" arr[1, 2] # ["b", "c"] arr[0..1] # ["a", "b"] arr << "d" # append arr.push("e") arr.pop arr.shift arr.unshift("z") arr.length arr.empty? arr.include?("b") arr.join(",")
Array Transformations
nums = [1, 2, 3, 4] nums.map { |n| n * 2 } # [2, 4, 6, 8] nums.select(&:even?) # [2, 4] nums.reject(&:even?) # [1, 3] nums.partition(&:even?) # [[2, 4], [1, 3]] nums.sum # 10 nums.minmax # [1, 4] nums.sort nums.reverse nums.uniq nums.compact # remove nil
Ranges
(1..5).to_a # [1, 2, 3, 4, 5] (1...5).to_a # [1, 2, 3, 4] ("a".."d").to_a # ["a", "b", "c", "d"] (1..).take(3) # [1, 2, 3], endless range (..5).cover?(3) # true, beginless range
Hashes
user = { name: "Ada", admin: true }
user[:name]
user[:email] = "ada@example.com"
user.fetch(:name) # raises KeyError if missing
user.fetch(:role, "student") # default value
user.key?(:admin)
user.values
user.keys
user.delete(:admin)
user.merge(role: "engineer") # new hash
user.merge!(active: true) # mutateHash Defaults
counts = Hash.new(0) counts["ruby"] += 1 # Default arrays need a block, not Hash.new([]) groups = Hash.new { |hash, key| hash[key] = [] } groups["backend"] << "Ruby"
Using Hash.new([]) shares one array across every missing key. The block form creates a fresh array per key.
Hash Iteration
user.each do |key, value| puts "#{key}=#{value}" end user.transform_keys(&:to_s) user.transform_values { |v| v.to_s.upcase } user.select { |key, value| value }
Sets
require "set" ids = Set.new([1, 2, 2, 3]) ids.include?(2) ids.add(4) ids.delete(1) ids | Set[3, 4, 5] # union ids & Set[2, 3] # intersection ids - Set[2] # difference