Skip to content

Instantly share code, notes, and snippets.

@JunichiIto
Created March 30, 2014 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JunichiIto/9870182 to your computer and use it in GitHub Desktop.
Save JunichiIto/9870182 to your computer and use it in GitHub Desktop.
Ruby: How to count for each word
str = "no ruby no life" #=> count as {"no"=>2,"ruby"=>1,"life"=>1}
Hash[str.scan(/\w+/).group_by{|s|s}.map{|k,v|[k,v.size]}]
str.scan(/\w+/).each_with_object(Hash.new(0)){|s,h|h[s]+=1}
# require Ruby 2.1.1
str.scan(/\w+/).group_by{|s|s}.map{|k,v|[k,v.size]}.to_h
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment