Juliusz
Juliusz

Reputation: 1370

Modifying object instance from inside a module

Is it possible to get/set instance variables of an object from inside a module which was included to the object class?

Upvotes: 0

Views: 63

Answers (1)

Miki
Miki

Reputation: 7188

Do you mean:

module Foo
  def bar
    @bar ||= 0
    @bar += 1
  end
end

class Tester
  include Foo
  def baz
    @bar ||= 0
    @bar += 500
  end
end

t = Tester.new
t.bar  #=> 1
t.baz  #=> 501
t.bar  #=> 502
t.bar  #=> 503
t.baz  #=> 1003

If so, then yes. On a somewhat related note, you might also find an explanation of difference between include and extend useful.

Upvotes: 1

Related Questions