Last active
August 29, 2015 14:01
-
-
Save lancetw/01a2ed683021a2cee4b7 to your computer and use it in GitHub Desktop.
each / inject / each_with_object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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