File: drop_last_while.rb

package info (click to toggle)
ruby-powerpack 0.1.1-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster, forky, sid, trixie
  • size: 492 kB
  • sloc: ruby: 819; makefile: 3
file content (21 lines) | stat: -rw-r--r-- 537 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
unless Enumerable.method_defined? :drop_last_while
  module Enumerable
    # Drops the last elements of an enumerable meeting a predicate.
    #
    # @return [Array] an array containing the remaining elements
    #
    # @example
    #   [1, 2, 3].drop_last_while(&:odd?) #=> [1, 2]
    def drop_last_while
      return to_enum(:drop_last_while) unless block_given?

      result = []
      dropping = true
      reverse_each do |obj|
        result.unshift(obj) unless dropping &&= yield(obj)
      end

      result
    end
  end
end