How to extend a method?

Class A
  attr_accessor :a
  def initialize
     self.a = 'a'
  end
end

I want to extend class A and add a new instance variable b. How can i do
this?

Class A
  attr_accessor :b
  def initialize

···

-----------------------------------------------
How can i initialize the variable b.
Must i rewrite the whole method, like
self.a = 'a'
self.b = 'b'
-----------------------------------------------
  end
end

Subclass C:

class B < A
  attr_accessor :b
  def intialize
    super # calls parent class (A) that already initializes @a
    @b = 'b'
  end
end

Regards
Florian

Florian Aßmann schrieb:

Subclass C:

class B < A
  attr_accessor :b
  def intialize
    super # calls parent class (A) that already initializes @a
    @b = 'b'
  end
end

Regards
Florian

module ExtendA
  attr_accessor :b
  def self.included(base)
    base.instance_variable_set :@b, 'b'
  end
end

class A
  include ExtendA
end

# There are probably 10^x ways to do this...

Regards
again

Thanks. Maybe using ExtendA module is a good start, :slight_smile:

I don't want to rewrite A class directly, but i want to extend it in my app.
Indeed, i want to extend Rails::Initializer, and when i start
a rails app, it can initialize the variable automatically.

Module R
    class A
        attr_accessor :b

        def self.run
           init = new B
           init.send(:process)
        end

        def process
           initize_a
        end

        def initize_a
           # other action using a.
        end
    end

    class B
        attr_accessor :a

        def initialize
           self.a = 'a'
        end
    end
end

I want to add a variable 'b' and initialize it when new a B. And then do
initialize_b when executing A#process.

Module R
     class A
       def initialize_b
       end
     end
end

I think Moduel ExtendB(as what you said) can be used to add a variable 'b'
and set the instance value.
But how can i directly initialize_b when executing A#process? I used to get
a A object and then invoke the initialize_b method.
But i didn't like that way? Is there a better way to directly inject the
code to the A#process?

Thank you.

···

On 9/3/07, Florian Aßmann <florian.assmann@email.de> wrote:

Florian Aßmann schrieb:
> Subclass C:
>
> class B < A
> attr_accessor :b
> def intialize
> super # calls parent class (A) that already initializes @a
> @b = 'b'
> end
> end
>
> Regards
> Florian
>
>

module ExtendA
  attr_accessor :b
  def self.included(base)
    base.instance_variable_set :@b, 'b'
  end
end

class A
  include ExtendA
end

# There are probably 10^x ways to do this...

Regards
again