Code Snippets
/

Ruby Array Methods Cheat Sheet

Ruby Array Methods Cheat Sheet

Ruby's `Enumerable` module gives `Array` a rich set of higher-order methods that replace most explicit loops. This snippet covers the trio you reach for daily (`map`, `select`, `reject`), reductions with `inject` / `reduce`, and grouping or slicing helpers like `group_by` and `each_slice`. Memorise these and most array transformations become a single chained pipeline.

Ruby
Easy
3 snippets
ruby-enumerables
map-filter-reduce
ruby-blocks

1,066 views

22

nums = [1, 2, 3, 4, 5, 6]

squares = nums.map { |n| n * n }
p squares # [1, 4, 9, 16, 25, 36]

evens = nums.select { |n| n.even? }
p evens   # [2, 4, 6]

odds = nums.reject { |n| n.even? }
p odds    # [1, 3, 5]

# &:method shorthand: equivalent to { |x| x.method }
p nums.map(&:to_s)   # ["1", "2", "3", "4", "5", "6"]

map (alias collect) returns a new array of the block's return values. select (alias filter) keeps elements where the block is truthy; reject keeps elements where it is falsy. The &:method shorthand turns a symbol into a proc that calls the method on each element, equivalent to { |x| x.to_s } but shorter. Chain them freely: nums.map(&:to_s).select { |s| s.size > 1 } reads top-to-bottom as a pipeline. None of these mutate the original array; their ! counterparts (map!, select!) do, but prefer the non-mutating forms unless you have a specific reason.