Stefano Crocco
2/20/2007 9:47:00 AM
Alle martedì 20 febbraio 2007, Chris Lowis ha scritto:
> 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.
>
> Kind regards,
>
> Chris
You don't need to do anything special to be able to do what you want. You only
need to replace the line
m=@signal.mean
with
m=mean
which means
m=self.mean
Methods called without an explicit receiver called using self as receiver.
Since you're inside the definition of an instance method of class MySignal,
self is an instance of class MySignal, and has a method called mean.
I hope this helps
Stefano