diff --git a/spec/std/enumerable_spec.cr b/spec/std/enumerable_spec.cr index f15ce053216e..04d46c7976a3 100644 --- a/spec/std/enumerable_spec.cr +++ b/spec/std/enumerable_spec.cr @@ -131,6 +131,20 @@ describe "Enumerable" do end end + describe "#to_set" do + context "without block" do + it "creates a Set from the unique elements of the collection" do + {1, 1, 2, 3}.to_set.should eq Set{1, 2, 3} + end + end + + context "with block" do + it "creates a Set from running the block against the collection's elements" do + {1, 2, 3, 4, 5}.to_set { |i| i // 2 }.should eq Set{0, 1, 2} + end + end + end + describe "chunk" do it "works" do [1].chunk { true }.to_a.should eq [{true, [1]}] diff --git a/src/set.cr b/src/set.cr index ca3addf72c9a..091352302c7d 100644 --- a/src/set.cr +++ b/src/set.cr @@ -495,4 +495,14 @@ module Enumerable def to_set : Set(T) Set.new(self) end + + # Returns a new `Set` with the unique results of running *block* against each + # element of the enumerable. + def to_set(&block : T -> U) : Set(U) forall U + set = Set(U).new + each do |elem| + set << yield elem + end + set + end end