Module: Corefines::Enumerable::Many

Defined in:
lib/corefines/enumerable.rb

Instance Method Summary collapse

Instance Method Details

#many?Boolean #many? {|obj| ... } ⇒ Boolean

Returns true if the enumerable has more than one element.

This method is functionally equivalent to enum.to_a.size > 1, or enum.select { ... }.length > 1 when the block is given.

Examples:

[1].many?             # => false
[1, 2].many?          # => true
[1, 2, 3].many?       # => true
[1, nil].many?        # => true
[1, 2, 3].many? { |n| n > 2 }  # => false

Overloads:

  • #many? {|obj| ... } ⇒ Boolean

    Returns true if the block returns a truthy value (i.e. other than nil and false) more than once.

    Yields:

    • (obj)

      gives each element to the block.


61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/corefines/enumerable.rb', line 61

module Many
  Support.classes_including_module(::Enumerable) do |klass|

    refine klass do
      def many?
        cnt = 0
        if block_given?
          any? do |element|
            cnt += 1 if yield element
            cnt > 1
          end
        else
          any? { (cnt += 1) > 1 }
        end
      end
    end
  end
end