Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Enumerable(T)#to_set(& : T -> U) : Set(U) forall U #12654

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions spec/std/enumerable_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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]}]
Expand Down
10 changes: 10 additions & 0 deletions src/set.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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