Forum: Ruby Help with Class design

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A8486651a974d7d9ecc35d25de96c7ee?d=identicon&s=25 Chris Lowis (chrislo)
on 2007-02-20 10:38
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
C40020a47c6b625af6422b5b1302abaf?d=identicon&s=25 Stefano Crocco (crocco)
on 2007-02-20 10:48
(Received via mailing list)
Alle martedì 20 febbraio 2007, Chris Lowis ha scritto:
>     @signal = input
>     var = @signal.inject(0) { |var, x| var += (x - m) ** 2 }
>    puts a.mean
> specific to my problem.
> 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
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2007-02-20 10:57
(Received via mailing list)
On 20.02.2007 10:38, Chris Lowis wrote:
>     @signal = input
>     var = @signal.inject(0) { |var, x| var += (x - m) ** 2 }
>    puts a.mean
> 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
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2007-02-20 11:02
(Received via mailing list)
On 2/20/07, Chris Lowis <chris.lowis@gmail.com> wrote:
>     @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
>
>
>
> --
> Posted via http://www.ruby-forum.com/.
>
>
HTH
Robert
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2007-02-20 11:04
(Received via mailing list)
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
D032dc2ce8e6e785161fb4e3ebb64ba3?d=identicon&s=25 Kalman Noel (Guest)
on 2007-02-20 11:21
(Received via mailing list)
Chris Lowis:
>     @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
A8486651a974d7d9ecc35d25de96c7ee?d=identicon&s=25 Chris Lowis (chrislo)
on 2007-02-20 11:29
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" ?
Ffcb418e17cac2873d611c2b8d8d891c?d=identicon&s=25 unknown (Guest)
on 2007-02-20 11:39
(Received via mailing list)
>>    end
>   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
Ffcb418e17cac2873d611c2b8d8d891c?d=identicon&s=25 unknown (Guest)
on 2007-02-20 11:48
(Received via mailing list)
> 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.
A8486651a974d7d9ecc35d25de96c7ee?d=identicon&s=25 Chris Lowis (chrislo)
on 2007-02-20 12:08
> 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
85ae830f08b5ff5e39a1cbae9e3d0205?d=identicon&s=25 Olivier Renaud (Guest)
on 2007-02-20 12:46
(Received via mailing list)
>     end
> 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 :)
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2007-02-20 12:52
(Received via mailing list)
On 2/20/07, Chris Lowis <chris.lowis@gmail.com> wrote:
>
> def diff()
>     result = []
>     @signal.each_index do |i|
>       result << @signal[i+1] - @signal[i] unless i == (@signal.length -
> 1)
>     end
>     result
> end

>
def diff
  r= []
  @signal.inject{|a,b| r << (b-a); b}
  Signal.new( r )
end
HTH
Robert
1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 unknown (Guest)
on 2007-02-20 13:09
(Received via mailing list)
Hi --

On Tue, 20 Feb 2007, Chris Lowis wrote:

>>    end
>
> removing the assignment "m = mean" ?

The disadvantage of that is that it will call the method mean once for
each iteration.  So you're better off storing it in a local variable.


David
Ffcb418e17cac2873d611c2b8d8d891c?d=identicon&s=25 unknown (Guest)
on 2007-02-20 13:27
(Received via mailing list)
> method :
> 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 ?

Get it to wrap the array in to a signal, and return that.

So, at the end of the method you'll do something like:

  ...
  end
  Signal.new(result)
end

Cheers,
  Benj
A8486651a974d7d9ecc35d25de96c7ee?d=identicon&s=25 Chris Lowis (chrislo)
on 2007-02-20 16:36
> Signal.new(result)

Thanks to all who gave the solution, it seems obvious now I've had it
pointed out to me ! I guess the question for me now is whether
signal.diff is still a signal or not, and if not, perhaps I need a
different kind of class to represent these objects.

Can you recommend books/tutorials for any (computer) language that deal
with modelling a non-trivial system using objects ? A lot of the
examples I have seen up to now are quite simple .

Chris
This topic is locked and can not be replied to.