Count of methods in Ruby just drop during object creation
Why does the total count of methods reduce, from 81 to 46 while instantiating an object from 'Class' class-objects?
Here's the code I'm running:
class Automobile
def wheels(wheel)
puts "#{wheel}"
end
end
class Car < Automobile
def gears
puts "Automatic Transmission"
end
end
limo = Car.new
benz = Automobile.new
puts Automobile.methods.count
puts Car.methods.count
puts benz.开发者_如何学JAVAmethods.count
puts limo.methods.count
I guess subclass is not inheriting certain methods, I thought they are class methods, so I did some tests and realized methods displayed by "puts Anyclass.methods" are not class methods. They must be instance methods.
How is this achieved in Ruby, to deter a subclass from inheriting certain methods?
Your entire question seems to be based on the incorrect belief that the result of Car.methods
is not the class methods of the Car class, but its instance methods. The result of Car.methods
is the list of methods of the Car class itself. To get the instance methods, you would have to write Car.instance_methods
. That's why you see that the instances have fewer methods than the classes.
For me, here are the results of running your code:
puts Automobile.methods.count
#=> 95
puts Car.methods.count
#=> 95 (exactly as you'd expect, since it didn't define any new class methods)
puts benz.methods.count
#=> 57 (this is 1 more than the result of Object.instance_methods.count, since you added #wheels)
puts limo.methods.count
#=> 58 (1 more than benz.methods.count, since you added #gears)
精彩评论