Skip to content

Instantly share code, notes, and snippets.

@peter
Created September 7, 2011 14:09
Show Gist options
  • Select an option

  • Save peter/1200655 to your computer and use it in GitHub Desktop.

Select an option

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

kotp commented Sep 12, 2011

Copy link
Copy Markdown

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

@peter

peter commented Sep 12, 2011

Copy link
Copy Markdown
Author

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