diff --git a/spec/std/enumerable_spec.cr b/spec/std/enumerable_spec.cr index f7e429bd79a2..34478d5c5f3b 100644 --- a/spec/std/enumerable_spec.cr +++ b/spec/std/enumerable_spec.cr @@ -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 diff --git a/src/enumerable.cr b/src/enumerable.cr index dbbf2adc2073..f13610485e8a 100644 --- a/src/enumerable.cr +++ b/src/enumerable.cr @@ -1291,4 +1291,16 @@ module Enumerable(T) hash[item[0]] = item[1] end end + + # Creates a `Hash` out of `Tuple` pairs (key, value) returned from the *block*. + # + # ``` + # (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| + key, value = yield item + hash[key] = value + end + end end