Ruby Enumerator "Single" method

71 Views Asked by At

I really need to make use of something similar to the Single method, which:

Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.

Obviously I can add an extension/refinement for convenience.

But does something similar already exists? Maybe in ActiveSupport or other library?

1

There are 1 best solutions below

7
On

No, nothing in the Standard Library (nor ActiveSupport, I believe), but easy enough to implement.

module EnumeratorWithSingle
  class TooManyValuesException < StandardError; end
  class NotEnoughValuesException < StandardError; end

  refine Enumerator do
    def single
      val = self.next
      begin
        self.next
        raise TooManyValuesException
      rescue StopIteration
        val
      end
    rescue StopIteration
      raise NotEnoughValuesException
    end
  end
end

module Test
  using EnumeratorWithSingle    
  puts [1].each.single            # 1
  puts [1, 2].each.single         # EnumeratorWithSingle::TooManyValuesException
end