Enumerable#avg is an average method for ruby’s enumerable module
Surprisingly, ActiveSupport’s core extensions don’t define a helpful average function in the Enumerable module.
wart:x3 huned$ script/console
Loading development environment (Rails 2.3.4)
>> [1,2,3,4].avg
NoMethodError: undefined method `avg' for [1, 2, 3, 4]:Array
from (irb):1
The absence of an average method is strange given that Enumerable#sum is defined and that it’d be trivially simple to implement. So monkeypatch config/initializers/enumerable.rb thusly:
Now we’re good.
wart:x3 huned$ script/console Loading development environment (Rails 2.3.4) >> [1,2,3].avg => 2.0 >> [1,2,3,4,5,6].avg => 3.5
Note that unlike ActiveSupport’s Enumerable#sum this method doesn’t accept an optional block.
About this entry
You’re currently reading “Enumerable#avg is an average method for ruby’s enumerable module,” an entry on e-huned.com
- Published:
- 11.17.09 / 9am
- Category:
- personal
2 Comments
Jump to comment form | comments rss [?] | trackback uri [?]