Reputation: 1572
class Person
def name
puts "Doharey"
end
end
puts Person.class #=> this out puts Class
puts Class.methods.count #=> 82 methods
puts Person.methods.count #=> 82 methods
In the above example a Person
class is created which inherits from Class
and both Person
and Class
has equal number of methods.
Now lets instantiate Person
class
a = Person.new
puts a.methods.count #=> 42 methods
If a
is an instance of Person
then why are the number of methods less in a
than Person
. What happens ? how some methods go missing ? Are they not inherited in the first place ? If so how ?
Upvotes: 1
Views: 89
Reputation: 14881
class Person
def name
puts "Doharey"
end
end
How many instance methods are there in our new class?
Person.instance_methods.size
# => 72
List all instance methods of a class, excluding any methods inherited from the superclass:
Person.instance_methods(false)
# => [:name]
Every new class is by default a subclass of Object:
Person.superclass
# => Object
How many instance methods are there in the superclass?
Object.instance_methods.size
# => 71
Upvotes: 1
Reputation: 7856
a.methods
are the instance methods and
Person.methods
are class methods. They do not share the same namespace. When you define name
on Person
you are defining an instance methods.
class Person
def self.name
puts "Doharey"
end
end
=> nil
Person.methods.count
=> 113
Class.methods.count
=> 114
Here I've defined a class method which also shows up in the method list.
Upvotes: 2