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#to_h(&block) #7150

Merged
merged 3 commits into from
Dec 7, 2018
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 4 additions & 0 deletions spec/std/enumerable_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -872,5 +872,9 @@ describe "Enumerable" do
it "for array" do
[[:a, :b], [:c, :d]].to_h.should eq({:a => :b, :c => :d})
end

it "with block" do
(1..3).to_h { |i| {i, i ** 2} }.should eq({1 => 1, 2 => 4, 3 => 9})
end
end
end
13 changes: 13 additions & 0 deletions src/enumerable.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1291,4 +1291,17 @@ module Enumerable(T)
hash[item[0]] = item[1]
end
end

# Creates a `Hash` out of an returned from a *block* Enumerable, where each
# element is a 2 element structure (for instance a `Tuple` or an `Array`).
Sija marked this conversation as resolved.
Show resolved Hide resolved
#
# ```
# (1..3).to_h { |i| {i, i ** 2} } # => {1 => 1, 2 => 4, 3 => 9}
# ```
def to_h(&block : T -> Tuple(K, V)) forall K, V
each_with_object({} of K => V) do |item, hash|
item_pair = yield item
Sija marked this conversation as resolved.
Show resolved Hide resolved
hash[item_pair[0]] = item_pair[1]
end
end
end