Skip to content

Instantly share code, notes, and snippets.

@lancetw
Last active August 29, 2015 14:01
Show Gist options
  • Save lancetw/01a2ed683021a2cee4b7 to your computer and use it in GitHub Desktop.
Save lancetw/01a2ed683021a2cee4b7 to your computer and use it in GitHub Desktop.
each / inject / each_with_object
class String
def count_words
h = Hash.new(0)
self.downcase.gsub(/[[:punct:]]/, '').split.each { |w| h[w] += 1 }
return h
end
end
#print 'a b c d e a b a a b c d d e f'.count_words #=> {"a"=>4, "b"=>3, "c"=>2, "d"=>3, "e"=>2, "f"=>1}
class String
def count_words
self.downcase.gsub(/[[:punct:]]/, '').split.inject(Hash.new(0)) { |h, w| h[w] += 1; h }
end
end
#print 'a b c d e a b a a b c d d e f'.count_words #=> {"a"=>4, "b"=>3, "c"=>2, "d"=>3, "e"=>2, "f"=>1}
class String
def count_words
self.downcase.gsub(/[[:punct:]]/, '').split.each_with_object(Hash.new(0)) { |w, h| h[w] += 1 }
end
end
#print 'a b c d e a b a a b c d d e f'.count_words #=> {"a"=>4, "b"=>3, "c"=>2, "d"=>3, "e"=>2, "f"=>1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment