C
Chris Lowis
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
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