1

Singleメソッドに似たものを実際に利用する必要があります。

シーケンスの唯一の要素を返し、シーケンスに要素が 1 つだけない場合は例外をスローします。

明らかに、便宜上拡張/改良を追加できます。

しかし、似たようなものはすでに存在しますか?多分ActiveSupportまたは他のライブラリにありますか?

4

1 に答える 1

2

いいえ、標準ライブラリには何もありません (ActiveSupport もそうだと思います) が、実装は簡単です。

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
于 2016-08-18T00:47:37.613 に答える