Ruby Enumerable ๐Ÿ“š Module: Exciting Methods

Enumerable is a collection of iteration methods, a Ruby module, and a big part of what makes Ruby a great programming language.

# count elements that evaluate to true inside a block
[1,2,34].count
=> 3

# Group enumerable elements by the block return value. Returns a hash
[12,3,7,9].group_by {|x| x.even? ? 'even' : 'not_even'}
=> {"even" => [12], "not_even" => [3, 7, 9]}

# Partition into two groups. Returns a two-dimensional array
> [1,2,3,4,5].partition { |x| x.even? }
=> [[2, 4], [1, 3, 5]]

# Returns true if the block returns true for ANY elements yielded to it
> [1,2,5,8].any? 4
=> false

> [1,2,5,8].any? { |x| x.even?}
=> true

# Returns true if the block returns true for ALL elements yielded to it
> [2,5,6,8].all? {|x| x.even?}
=> false

# Opposite of all?
> [2,2,5,7].none? { |x| x.even?}
=> false

# Repeat ALL the elements n times
> [3,4,6].cycle(3).to_a
=> [3, 4, 6, 3, 4, 6, 3, 4, 6]

# select - SELECT all elements which pass the block
> [18,4,5,8,89].select {|x| x.even?}
=> [18, 4, 8]
> [18,4,5,8,89].select(&:even?)
=> [18, 4, 8]

# Like select, but it returns the first thing it finds
> [18,4,5,8,89].find {|x| x.even?}
=> 18

# Accumulates the result of the previous block value & passes it into the next one. Useful for adding up totals
> [4,5,8,90].inject(0) { |x, sum| x + sum }
=> 107
> [4,5,8,90].inject(:+)
=> 107
# Note that 'reduce' is an alias of 'inject'.

# Combines together two enumerable objects, so you can work with them in parallel. Useful for comparing elements & for generating hashes

> [2,4,56,8].zip [3,4]
=> [[2, 3], [4, 4], [56, nil], [8, nil]]

# Transforms every element of the enumerable object & returns the new version as an array
> [3,6,9].map { |x| x+89-27/2*23 }
=> [-207, -204, -201]

What is :+ in [4, 5, 8, 90].inject(:+) in Ruby?

๐Ÿ”ฃ :+ is a Symbol representing the + method.

In Ruby, every operator (like +, *, etc.) is actually a method under the hood.

  • inject takes a symbol (:+)
  • Ruby calls .send(:+) on each pair of elements
  • It’s equivalent to:
    (((4 + 5) + 8) + 90) => 107

๐Ÿ”ฃ &: Explanation:

  • :even? is a symbol representing the method even?
  • &: is Ruby’s “to_proc” shorthand, converting a symbol into a block
  • So &:even? becomes { |n| n.even? } under the hood

Enjoy Enumerable ๐Ÿš€