Skip to content

Instantly share code, notes, and snippets.

@rubysolo
Created January 20, 2010 20:23
Show Gist options
  • Select an option

  • Save rubysolo/282214 to your computer and use it in GitHub Desktop.

Select an option

Save rubysolo/282214 to your computer and use it in GitHub Desktop.
list = [1, 1, 2, 2, 3]
# using each:
hash = {}
list.each do |item|
hash[item] ||= 0
hash[item] += 1
end
# using inject:
hash2 = list.inject({}) do |h, item|
h.update(item => (h[item] || 0) + 1)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment