Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby pass self as instance in initialize

Tags:

ruby

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?

like image 202
Cato Yeung Avatar asked Sep 01 '12 09:09

Cato Yeung


People also ask

Is initialize a class or instance method Ruby?

Its purpose is to create a new instance of the class. You can call this method yourself to create uninitialized instances of a class. But don't try to override it; Ruby always invokes this method directly, ignoring any overriding versions you may have defined. initialize is an instance method.

What does def self mean in Ruby?

def name puts self end name # => main Copy. This code defines and calls a . name method which prints the value of self. self is initially set to main , an instance of the Object class that is automatically created whenever a Ruby program is interpreted. The main object is the "top-level" namespace of the program.


1 Answers

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
like image 133
Michael Kohl Avatar answered Oct 12 '22 23:10

Michael Kohl