Skip to content

Instantly share code, notes, and snippets.

@bestie
Created June 15, 2016 20:13
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 bestie/30a2457ba506596d3110f20d4f029551 to your computer and use it in GitHub Desktop.
Save bestie/30a2457ba506596d3110f20d4f029551 to your computer and use it in GitHub Desktop.
Imperative `Hash.new` vs functional
# Task: Count how many users have each favorite color
User = Struct.new(:id, :favorite_color)
colors = [:red, :green, :blue, :hot_pink]
users = 10.times.map { |n| User.new(n, colors.sample) }
# The follow two example print the same result
## Imperative approach
counts = Hash.new(0)
users.each do |user|
counts[user.favorite_color] += 1
end
p counts
## Functional approach
p Hash[
users
.group_by(&:favorite_color)
.map { |color, users| [color, users.count] }
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment