On Mon, Jul 5, 2010 at 11:22 PM, David Masover <ninja / slaphack.com> wrote:
> On Monday, July 05, 2010 03:30:44 pm Fearless Fool wrote:
>> Assume I'd like to create a statistics package designed to work on
>> Arrays [but see P.S.]. =A0One way to do this would be to create function=
s
>> that take an array as an argument:
>>
>> =A0 def mean(array)
>> =A0 =A0 return NaN unless array && array.size > 0
>> =A0 =A0 array.reduce(0.0) {|accum, val| accum + val} / array.size
>> =A0 end
>>
>> ... but that's so old school. =A0What I'd really like is to *cleanly*
>>
>> extend the Array class so you can operate on it directly, as in:
>> =A0 >> [1, 2, 3].mean
>>
>> =A0 =3D> 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:
>>
>> =A0 class Array
>> =A0 =A0 def mean
>> =A0 =A0 =A0 return NaN unless self.size > 0
>> =A0 =A0 =A0 self.reduce(0.0) {|accum, val| accum + val} / self.size
>> =A0 =A0 end
>> =A0 end
>
> What kind of surprises?
>
>> My hunch is that the stats functions should be wrapped in a module and
>> then included (extended?) when desired. =A0But despite reading the
>> tutorials and docs, I'm not sure what's considered the stylistically
>> correct way (and the syntax) to package that up.
>
> Simple enough:
>
> module MyModule
> =A0def mean
> =A0 =A0...
> =A0end
> end
>
> Then, you can always do this:
>
> [].extend MyModule

I agree, this is the less dangerous thing to do: just extend the
specific array instances with your functionality. That way, all other
arrays are left intact.

Jesus.