Monster on Fire

09 June 2018

    Tags:
  • Ruby
  • tips
  • TIL

TIL each_with_object

Objective:

To count the occurrence of words in a string

Bonus: Don't use a temporary variable

Example:

olly: 2 in: 1 come: 1 free: 1

Without using 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}

Using 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}