Skip to content

Instantly share code, notes, and snippets.

@peter
Created September 7, 2011 14:09
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 peter/1200655 to your computer and use it in GitHub Desktop.
Save peter/1200655 to your computer and use it in GitHub Desktop.
Ruby inject example, concise and yet readable?
# 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
Copy link

kotp commented Sep 12, 2011

The fact that the first value in your array is 1 may cause misleading assumptions.

@peter
Copy link
Author

peter commented Sep 12, 2011

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