Slide 16
Slide 16 text
Trick 14
Enumerable#each_with_object vs. inject
If you need to return the object inside reduce or inject, make use of each_with_object.
# not so good
(1..10).reduce(Hash.new(0)) { |hash, i| hash[i] = i*2; hash }
# => {1=>2, 2=>4, 3=>6, 4=>8, 5=>10, 6=>12, 7=>14, 8=>16, 9=>18, 10=>20}
# better
(1..10).each_with_object(Hash.new(0)) { |i, hash| hash[i] = i*2 }
# => {1=>2, 2=>4, 3=>6, 4=>8, 5=>10, 6=>12, 7=>14, 8=>16, 9=>18, 10=>20}
16 / 27