[ruby-talk:02513] Re: Refering to another instance with a method

From: Dave Thomas <Dave@...>
Date: 2000-04-19 18:20:16 UTC
List: ruby-talk #2513
"David Douthitt" <DDouthitt@cuna.com> writes:

> I have a situation where I want to copy values from one instance to
> another with a particular method.  Put another way, I want to set
> values in an instance to default values after the instance has been
> created.  The default values may or may not be known at instance
> creation time.

Which version of Ruby are you using? With 1.5.3, you could use the new 
class variables for this.

     class MyClass
       @@defaultWidth = 10
       @@defaultColor = :red

       attr_accessor :width, :color

       # class methods to change the defaults
       def MyClass.defaultWidth=(w)
         @@defaultWidth = w
       end
       def MyClass.defaultColor=(c)
         @@defaultColor = c
       end

       # instance method to reset instance variables
       # to default values

       def reset
         @width = @@defaultWidth
         @color = @@defaultColor
       end

       def initialize
         reset
       end

       # other stuff
     end

     m = MyClass.new
     p m
     m.width = 100
     m.color = :blue
     p m
     MyClass.defaultWidth = 20
     m.reset
     p m

With earlier Rubys, you can fake out the same effect using a class
constant that references (say) a Hash

     class MyClass
       DEFAULTS = { 'width' => 10, 'color' => :red }

       attr_accessor :width, :color

       # class methods to change the defaults
       def MyClass.defaultWidth=(w)
         DEFAULTS['width'] = w
       end
       def MyClass.defaultColor=(c)
         DEFAULTS['color'] = c
       end

       # instance method to reset instance variables
       # to default values

       def reset
         @width = DEFAULTS['width']
         @color = DEFAULTS['color']
       end

       def initialize
         reset
       end

       # other stuff
     end

     m = MyClass.new
     p m
     m.width = 100
     m.color = :blue
     p m
     MyClass.defaultWidth = 20
     m.reset
     p m

> As a corollary to #2, tell me how these work (or don't):
> 
 class MyClass
    myvar1 = "a"
    @myvar2 = "b"

    def method
       p myvar1, @myvar2
    end
    end

This isn;t quite doing what you think it might. @myvar is indeed an
instance method, so it a new version is created for each instance.

myvar1 however is a local variable in the scope of the class
definition. Unlike the new class variables (@@myvar1), it is not
available to instances.



Regards


Dave

In This Thread

Prev Next