Skip to content

Commit

Permalink
Add Enumerable#to_h(&block)
Browse files Browse the repository at this point in the history
  • Loading branch information
Sija committed Dec 5, 2018
1 parent 3021206 commit 9863fca
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
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
10 changes: 10 additions & 0 deletions src/enumerable.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1291,4 +1291,14 @@ 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`).
#
# ```
# (1..3).to_h { |i| {i, i ** 2} } # => {1 => 1, 2 => 4, 3 => 9}
# ```
def to_h(&block : T -> U) forall U
map(&block).to_h
end
end

0 comments on commit 9863fca

Please sign in to comment.