Count of methods in Ruby just drop during object creation

不羁岁月 提交于 2019-12-12 01:56:34

问题


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.methods.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?


回答1:


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)


来源:https://stackoverflow.com/questions/7249148/count-of-methods-in-ruby-just-drop-during-object-creation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!