Created
August 24, 2012 16:48
-
-
Save kbaribeau/3452778 to your computer and use it in GitHub Desktop.
Ruby style poll
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
#Do you prefer this? | |
merchant["thing"] = important_stuff.map { |important_thing| important_thing["units"] }.inject(&:+) | |
#Or this? | |
important_stuff.each { |important_thing| merchant["thing"] += important_thing["units"] } | |
#Why? Is it completely objective? Or are ruby's idioms/social mores/conventions the deciding factor? |
Forgot a :c => 0 in there
# easy to see we're doing x = y
hash = {}
hash[:a] = [1, 2, 3, 4].map { |x| x + 1 }.inject(&:+)
hash[:b] = "asdf123"
hash[:c] = [2, 9, 8].map { |x| x * 2 }.inject(&:+)
# have to scan around to see what's going on
hash = { :a => 0, :c => 0 }
[1, 2, 3, 4].each { |x| hash[:a] += (x + 1) }
hash[:b] = "asdf123"
[2, 9, 8].each { |x| hash[:c] += x * 2 }.inject(&:+)
I still like the .sum solution, but @fredericksgary's point is what makes me like #1 a little more than just an inject.
Is there something that makes a pure inject clearer than solution #1? Objectively, it's one loop vs two. You could argue that one loop is executing fewer instructions, but I think two simple loops is clearer than one (slightly) more complex one.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I vote for:
#1 sum
#2 a pure inject
#3 the top one
#4 the bottom one
I think the top one is easier to follow. You're setting something to the result of something else. In the bottom one you have to look into the bits of the loop to realize there's a mutation going on.