On 2/20/07, Chris Lowis <chris.lowis / gmail.com> wrote:
> I'm quite new to object-orientated programming and have a problem with a
> class I am trying to design. At the moment I have
>
> #!/usr/local/bin/ruby
>
> require 'mathn'
>
> class MySignal
>
>   def initialize(input)
>     @signal = input
>   end
>
>   def mean()
>     sum = 0;
>     @signal.each {|i| sum+=i}

you could use inject here too
@signal.inject{|s,i|s+i}
you do not need a start value, try this to see why
%w{Hello Brave Gnu World}.inject{|a,b| p [a,b]}
and
%w{Hello Brave Gnu World}.inject{|a,b| p [a,b]; b}
I just learned that recently from Ruby Quiz 113 ;)
http://www.rubyquiz.com/quiz113.html
but be aware that inject is slower

>     mean = sum/@signal.length
>   end
>
>   def variance()
>     m = @signal.mean

m = self.mean
(which is equivalent to m = mean unless a local variable exists)

>     var = @signal.inject(0) { |var, x| var += (x - m) ** 2 }
@signal.inject(0){|v,x| v + (x-m) ** 2 } # the start value is needed
here but assignment is an unnecessary step

again #each might be faster albeit less elegant, if you run into
performance issues

>     var = var/(@signal.length-1)
maybe you want to rescue ZeroDevision here?
begin ...
rescue ZeroDevisionError
end
>   end
> end
>
> I can create a new "signal" with :
>
>    a = MySignal.new([1,2,3])
>
> and calculate the mean with :
>
>    puts a.mean
>
> But if I try to calculate the variance:
>
>    puts a.variance
>
> ./signal.rb:18:in `variance': undefined method `mean' for [1, 2,
> 3]:Array (NoMethodError)
>
> Which makes sense, as @signal is an object with the Array class. I don't
> want to add methods to Ruby's array class as later my methods may be too
> specific to my problem.
>
> How do I write a class such that methods defined within it can "refer"
> to each other, for example "variance" can call and use "mean" ? I am
> sure this question arises from my lack of familiarity with
> object-orientated programming. In addition to suggestions for the
> specific problem above, any pointers to references that could help me
> learn more general OO-design would also be appreciated.
>
> Kind regards,
>
> Chris
>
> --
> Posted via http://www.ruby-forum.com/.
>
>
HTH
Robert

-- 
We have not succeeded in answering all of our questions.
In fact, in some ways, we are more confused than ever.
But we feel we are confused on a higher level and about more important things.
-Anonymous