[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Help with Class design

Chris Lowis

2/20/2007 9:39:00 AM

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

--
Posted via http://www.ruby-....

14 Answers

Stefano Crocco

2/20/2007 9:47:00 AM

0

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

Robert Klemme

2/20/2007 9:54:00 AM

0

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

Robert Dober

2/20/2007 10:02:00 AM

0

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/qu...
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-....
>
>
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

Robert Dober

2/20/2007 10:03:00 AM

0

On 2/20/07, Robert Dober <robert.dober@gmail.com> wrote:

>
> m = self.mean
> (which is equivalent to m = mean unless a local variable exists)
a local variable "mean" exists
Stupid me !
>

R

Kalman Noel

2/20/2007 10:11:00 AM

0

Chris Lowis:
> 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 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.

Kalman

Chris Lowis

2/20/2007 10:29:00 AM

0

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" ?



--
Posted via http://www.ruby-....

benjohn

2/20/2007 10:38:00 AM

0

> 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-....
>
>



benjohn

2/20/2007 10:47:00 AM

0

> 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" ?

I wrote about removing the "m=mean" in another post...

I don't think the above will work, and even if it does, I would advise
very strongly against putting an assignment in to your inject block. It
breaks the semantics of what people (well, me anyway) expect inject to
do. What you're trying to do with inject is make a more "functional"
program; you're trying to avoid assigning to things; you're closer to
saying what you want done, rather than how you want it done (declarative
verses imperative style). If you start making assignments, you break
away from that style.




Chris Lowis

2/20/2007 11:09:00 AM

0

> What you're trying to do with inject is make a more "functional"
> program; you're trying to avoid assigning to things; you're closer to
> saying what you want done, rather than how you want it done (declarative
> verses imperative style). If you start making assignments, you break
> away from that style.

I think I understand what you mean, but I am so used to programming in
languages where assignments are common place (eg. Matlab) that I am
struggling to adjust to this new way of thinking. For example I have a
method :

def diff()
result = []
@signal.each_index do |i|
result << @signal[i+1] - @signal[i] unless i == (@signal.length -
1)
end
result
end

which takes a @signal object and returns an array of the differences
between each successive element of signal. But now I cannot write

a = MySignal.new([1,2,3])
a.diff.variance

because diff has returned an object of class "array" and the variance
method is not defined . How do I write "diff" in someway that it gives
me a new "signal" instead of an array ?

Thank you all for your help !

Chris



--
Posted via http://www.ruby-....

Olivier

2/20/2007 11:46:00 AM

0

> I think I understand what you mean, but I am so used to programming in
> languages where assignments are common place (eg. Matlab) that I am
> struggling to adjust to this new way of thinking. For example I have a
> method :
>
> def diff()
> result = []
> @signal.each_index do |i|
> result << @signal[i+1] - @signal[i] unless i == (@signal.length -
> 1)
> end
> result
> end
>
> which takes a @signal object and returns an array of the differences
> between each successive element of signal. But now I cannot write
>
> a = MySignal.new([1,2,3])
> a.diff.variance
>
> because diff has returned an object of class "array" and the variance
> method is not defined . How do I write "diff" in someway that it gives
> me a new "signal" instead of an array ?
>
> Thank you all for your help !
>
> Chris

You want to return a new Signal so... just do it !

def diff()
result = []
@signal.each_index do |i|
result << @signal[i+1] - @signal[i] unless i == (@signal.length-1)
end
return MySignal.new(result)
end

Maybe I missed something in your question, or maybe you would like your class
MySignal to act more like an Array. If so, there are many solutions (in order
of preference) :

* Use the Forwardable module to give access to specific methods from Array
* Use the Delegate lib to delegate all unknown methods to Array
* Make your class a subclass of Array (but delegation is almost always better)
* Reopen Array and add extra features (but this should be reserved for some
specific needs, not in your case)

I hope I answered your question :)

--
Olivier Renaud