Created
June 15, 2016 20:13
-
-
Save bestie/30a2457ba506596d3110f20d4f029551 to your computer and use it in GitHub Desktop.
Imperative `Hash.new` vs functional
This file contains hidden or 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
# 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