Created
September 7, 2011 14:09
-
-
Save peter/1200655 to your computer and use it in GitHub Desktop.
Ruby inject example, concise and yet readable?
This file contains 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
# Traditional idiom | |
total = 1 | |
[2, 3, 5].each do |value| | |
total = total * value | |
end | |
puts total | |
# Ruby idiom | |
puts [2, 3, 5].inject { |mult, value| mult * value } |
kotp: thanks, didn't think about that. I changed the first value to be 2.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The fact that the first value in your array is 1 may cause misleading assumptions.