From: Fearless Fool Date: 2010-07-06T05:30:44+09:00 Subject: extending a core class cleanly [noobish alert] Assume I'd like to create a statistics package designed to work on Arrays [but see P.S.]. One way to do this would be to create functions that take an array as an argument: def mean(array) return NaN unless array && array.size > 0 array.reduce(0.0) {|accum, val| accum + val} / array.size end ... but that's so old school. What I'd really like is to *cleanly* extend the Array class so you can operate on it directly, as in: >> [1, 2, 3].mean => 2.0 I'm sure that it's considered bad style to simply open the Array class and extend it, since that can lead to unexpected user surprises: class Array def mean return NaN unless self.size > 0 self.reduce(0.0) {|accum, val| accum + val} / self.size end end My hunch is that the stats functions should be wrapped in a module and then included (extended?) when desired. But despite reading the tutorials and docs, I'm not sure what's considered the stylistically correct way (and the syntax) to package that up. Comments? Pointers? Thanks! - ff [P.S.: Before you tell me about available stats packages, etc, note that I'm only using statistics as an example. My real question is about extending a class...] -- Posted via http://www.ruby-forum.com/.