[4, 5, 6, 7].inject(0) {|t,v| t + v}
I could clean this up and do something much simpler using inject, like so,
[4, 5, 6, 7].inject(:+)
What's more, you can run this too
[4, 5, 6, 7].inject(:-) [4, 5, 6, 7].inject(:*) [4, 5, 6, 7].inject(:/)
And check this out, say I want the average of the numbers in this array. I just run this:
[4, 5, 6, 7].instance_eval { inject(:+) / self.size.to_f }
Simply brilliant.
No comments:
Post a Comment