Skip to content

Commit

Permalink
Add Enumerable#one? (#7166)
Browse files Browse the repository at this point in the history
  • Loading branch information
asterite authored and RX14 committed Dec 9, 2018
1 parent 47725d1 commit 7b315d8
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
3 changes: 3 additions & 0 deletions spec/std/enumerable_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -733,6 +733,9 @@ describe "Enumerable" do
it { [1, 2, 2, 3].one? { |x| x == 1 }.should eq(true) }
it { [1, 2, 2, 3].one? { |x| x == 2 }.should eq(false) }
it { [1, 2, 2, 3].one? { |x| x == 0 }.should eq(false) }
it { [1, 2, false].one?.should be_false }
it { [1, false, false].one?.should be_true }
it { [false].one?.should be_false }
end

describe "partition" do
Expand Down
13 changes: 13 additions & 0 deletions src/enumerable.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1010,6 +1010,19 @@ module Enumerable(T)
c == 1
end

# Returns `true` if only one element in this enumerable
# is _truthy_.
#
# ```
# [1, false, false].one? # => true
# [1, false, 3].one? # => false
# [1].one? # => true
# [false].one? # => false
# ```
def one?
one? &.itself
end

# Returns a `Tuple` with two arrays. The first one contains the elements
# in the collection for which the passed block returned `true`,
# and the second one those for which it returned `false`.
Expand Down

0 comments on commit 7b315d8

Please sign in to comment.