module

Enumerable(T)

The Enumerable mixin provides collection classes with several traversal, searching, filtering and querying methods.

Including types must provide an each method, which yields successive members of the collection.

For example:

class Three
  include Enumerable(Int32)

  def each(&)
    yield 1
    yield 2
    yield 3
  end
end

three = Three.new
three.to_a                # => [1, 2, 3]
three.select &.odd?       # => [1, 3]
three.all? { |x| x < 10 } # => true

Note that most search and filter methods traverse an Enumerable eagerly, producing an Array as the result. For a lazy alternative refer to the Iterator and Iterable modules.

Instance methods

avg

Returns the average of a collection of numbers.

[1, 2, 3, 4, 5].avg
=> 3
Source
blank?

An enumerable is blank if it's empty.

[1,2,3].blank?
=> false
[].blank?
=> true

source: Rails ActiveSupport

Source
exactly?(count : Int32, &)

Checks if exactly n elements meet a certain predicate with a block.

  [1, 2, 3, 4].exactly?(1) { |n| n > 3 } #=> true
  [1, 2, 3, 4].exactly?(2, &.even?) #=> true
  [1, 1, 3, 3].exactly?(2, &.even?) #=> false
Source
excludes?(obj)

Returns true if the collection does not contains obj, false otherwise.

[1, 2, 3].excludes?(4) # => true
[1, 2, 3].excludes?(3) # => false

source: Rails ActiveSupport

Source
frequencies

Counts the number of occurrence of items in the enumerable.

  [].frequencies # => {}
  [1, :symbol, 'string', 3, :symbol, 1].frequencies
    #=> { 1 => 2, :symbol => 2, 'string' => 1, 3 => 1 }

source: Powerpack

Source
many?

Returns true if many elements fulfilled the block condition, much like any?, so people.many? { |p| p.age > 26 } returns true if more than one person is over 26.

source: Rails ActiveSupport

Source
many?

Returns true if the enumerable has more than 1 element. functionally equivalent to enum.size > 1.

source: Rails ActiveSupport

Source
pluck(*keys)

Convert an enumerable to an array based on the given key, throws an error if any key does not exists.

[{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pluck(:name)
=> ["David", "Rafael", "Aaron"]

[{ id: 1, name: "David" }, { id: 2, name: "Rafael" }].pluck(:id, :name)
=> [{1, "David"}, {2, "Rafael"}]

source: Rails ActiveSupport

Source
pluck?(*keys)

Convert an enumerable to an array based on the given key, returns nil if any key does not exists.

[{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pluck(:name)
=> ["David", "Rafael", "Aaron"]

[{ id: 1, name: "David" }, { id: 2, name: "Rafael" }].pluck(:id, :name)
=> [{1, "David"}, {2, "Rafael"}]

[{ id: 1, name: "David" }, { id: 2, name: "Rafael" }].pluck(:color)
=> []

[{ id: 1, name: "David" }, { id: 2, name: "Rafael" }].pluck(:id, :color)
=> [{1, nil}, {2, nil}]

source: Rails ActiveSupport

Source
without(*items)

Returns a copy of the enumerable without the specified items.

[1, 2, 3, 4, 5].without 3, 5
=> [1, 2, 4]

source: Rails ActiveSupport

Source