From: Robert Klemme Date: 2007-02-20T18:55:13+09:00 Subject: Re: Help with Class design On 20.02.2007 10:38, Chris Lowis 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} > mean = sum/@signal.length > end > > def variance() > m = @signal.mean > var = @signal.inject(0) { |var, x| var += (x - m) ** 2 } > var = var/(@signal.length-1) > 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. You just need to change the line to m = mean or - if you want to be more verbose - m = self.mean i.e. you just picked the wrong receiver for the call. Kind regards robert