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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With