Skip to content

Instantly share code, notes, and snippets.

@springaki
Created March 30, 2014 15:30
Show Gist options
  • Save springaki/9874454 to your computer and use it in GitHub Desktop.
Save springaki/9874454 to your computer and use it in GitHub Desktop.
"no ruby, no life!"
# => {"no"=>2,"ruby"=>1,"life"=>1}
str = "no ruby, no life!"
# A.1
str.scan(/\w+/).each_with_object(Hash.new(0)){|e,h| h[e]+=1}
# => {"no"=>2, "ruby"=>1, "life"=>1}
# A.2
# 意味ないけどこんなこともできるよね。
h = Hash.new {|hash, key| hash[key.uniq] = key.size }
str.scan(/\w+/).group_by{|s|s}.values.each{|e| h[e]}
# h
# => {["no"]=>2, ["ruby"]=>1, ["life"]=>1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment