Suresh
Suresh

Reputation: 235

Accessing methods in class body

Can somebody explain the following behavior?

def a_method
  "a_method() was called by #{self}"
end

class MyClass
  puts a_method
  def another_method
    puts a_method
  end
end

MyClass.new.another_method

It produces following output:

a_method() was called by MyClass
a_method() was called by #<MyClass:0x000000034962b0>

How does puts a_method within the MyClass body work? How could I access a_method while defining Myclass?

Upvotes: 2

Views: 114

Answers (3)

sawa
sawa

Reputation: 168121

(Outermost) Ruby statements are called and executed in the order they are written.

Within MyClass, there is a method call puts a_method, where self is the class MyClass. This prints the first line of your output. Then, later, there is a method call another_method, which calls puts a_method, where self is an instance of MyClass. This prints the second line of your output.

How could I access a_method while defining Myclass?

This seems to imply that you consider class definition to be completed when the (first occurrence of a) class body is closed. That is however not the case. A class is created right after you open the class body for the first time. Hence, in the class body, you can call methods on the class. Defining methods within a class body is not part of the creation of the class; the class is already there, and it is modifying the class.

Upvotes: 2

Tarun Agrawal
Tarun Agrawal

Reputation: 11

A class body executes when it initially loads(global variable, class variables and Constants are defined within it, and finally methods are defined).

So that a_method is called by MyClass when it is defined.

Upvotes: 1

sschmeck
sschmeck

Reputation: 7685

The first call is executed in Class scope. Therefore self is the class. The second is executed in instance scope of the class. You could add an class method to have the same effect like first method call.

def a_method                                
  "a_method() was called by #{self}"        
end                                         

class MyClass                               
  puts a_method # how this works?           

  def another_method                        
    puts a_method                           
  end                                       

  def self.a_class_method                   
    puts a_method                           
  end                                       
end                                         

MyClass.a_class_method                      
MyClass.new.another_method  

# result
a_method() was called by MyClass
a_method() was called by MyClass
a_method() was called by #<MyClass:0x00000002dc49f0>

Upvotes: 1

Related Questions