From: benjohn@... Date: 2007-02-20T19:38:28+09:00 Subject: Re: Help with Class design > Thank you all for your help, knowing exactly what "self" refers to in > each context seems to be the stumbling block for me at the moment. I'll > have to read about this some more, along with the documentation for some > of the Enumerables . > >> I suppose that you variance method should read something like >> >> def variance >> m = mean >> @signal.inject(0) { |sum, x| sum + (x-m)**2 } / @signal.length >> end >> >> Note that I prefer not using meaningless assignment in the inject >> block. > > And to that end, using the suggestions above, I suppose I could equally > well write : > > def variance() > @signal.inject(0) { |var, x| var += (x - mean) ** 2 } / > (@signal.length-1) > end > > removing the assignment "m = mean" ? You can, and I probably would, but you will then be calling the method "mean" a lot. In fact, for a signal of size n, you will find the mean n times, which makes your complexity scale n**2. However, you can make the method "mean" cache, or memoize the value it calulates: def mean @mean ||= calculate_mean end def calculate_mean @signal.inject {|s,x| s+x} / @signal.size end > > > > -- > Posted via http://www.ruby-forum.com/. > >