Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling instance method in Class in Ruby

Tags:

ruby

I am very confused about this. In Programming Ruby book, it says, "receiver checks for the method definition in its own class"

So class object stores all instance methods. Then why can't I call instance method from within a class?

For example:

class ExampleClass
  def example_method    
  end
  example_method
end

I cannot call example_method inside ExampleClass.

However, if I define a method in top level like this:

class ExampleClass
  def example_method
  end
end

def example_method1
end

example_method1

Then I can call top level method example_method1.

Isn't top level also a class? How come it is different than a calling instance method from within ExampleClass?

like image 824
meizin Avatar asked Oct 24 '25 14:10

meizin


2 Answers

The biggest reason that you cannot call that function in the way that you have written it is that it is, as you say, an instance method.

Try defining it in this way:

class ExampleClass
  def self.class_method
    puts "I'm a class method"
  end
  class_method
end

I believe you will find that you have a different result. It's not that it's "Top Level", it's whether or not it's in scope for what you're dealing with. Since you're dealing with a class, a class method would be necessary. If you're dealing with an object (an instantiated class) it's a different "scope".

like image 68
David Hoelzer Avatar answered Oct 26 '25 11:10

David Hoelzer


Those "global" methods are an exception. They are defined as private instance methods of Object. Everything inherits from Object, so these methods are "globally" visible.

p self.class # => Object
p self.private_methods.sort # => [:Array, :Complex, ... :using, :warn] # all (?) from Kernel module

def aaaa
end

p self.private_methods.sort # => [:aaaa, :Array,  ... :using, :warn]
like image 30
steenslag Avatar answered Oct 26 '25 11:10

steenslag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!