diff --git a/spec/std/enumerable_spec.cr b/spec/std/enumerable_spec.cr index 2bcc7d92ccb3..f75389f2f1a8 100644 --- a/spec/std/enumerable_spec.cr +++ b/spec/std/enumerable_spec.cr @@ -130,6 +130,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 2d70a8bde059..40ccd12f4653 100644 --- a/src/set.cr +++ b/src/set.cr @@ -486,4 +486,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