09 June 2018
To count the occurrence of words in a string
Bonus: Don't use a temporary variable
olly: 2 in: 1 come: 1 free: 1
each_with_object
new_hash = Hash.new(0)
words.each { |word| new_hash[word] += 1 }
new_hash # => {"olly"=>2, "in"=>1, "come"=>1, "free"=>1}
each_with_object
words.each_with_object(Hash.new(0)) { |word, new_hash| new_hash[word] += 1 }
# => {"olly"=>2, "in"=>1, "come"=>1, "free"=>1}