Cato Yeung
Cato Yeung

Reputation: 701

Ruby pass self as instance in initialize

def initialize()
  @attribute = AnotherClass.new(self)
end

I am going to ruby from python. In python, I know I can pass self as an object to a function. Now, I want to pass self to another class's initialize method. How can I do that?

Upvotes: 5

Views: 3704

Answers (1)

Michael Kohl
Michael Kohl

Reputation: 66867

Just the way you would expect:

class A
  def initialize(foo)
    @foo = foo
  end
end

class B
  attr_reader :bar

  def initialize
   @bar = A.new(self)
  end
end

B.new.bar.class #=> A

Upvotes: 5

Related Questions