Is Class declaration an eyewash in ruby? Is everything really object oriented?

喜夏-厌秋 提交于 2019-12-31 03:11:29

问题


class Person
  def name
   puts "Dave"
  end
end

puts Person.object_id

There are only two ways of accessing methods :

1) Someclass.method in case of class methods. #where Someclass is a class.

2) and Object.method when the method being accessed is a regular method declared inside a class. and Object is an instance of a class.

It follows the pattern Object.method so, does it mean Person class is really an object?

or object_id is a class method? The latter seems unlikely because class methods cannot be inherited into an instance. but when we do something like this :

a = Person.new
a.methods.include?("object_id") # this produces true

a is an instance of Person class so object_id cannot be a class method.


回答1:


Yes, Ruby classes are objects:

>> String.is_a? Object
=> true
>> String.methods.count
=> 131
>> Fixnum.methods.count
=> 128



回答2:


Yes, classes in Ruby are instances of class Class. In fact, you can create the same class just with:

Person = Class.new do
  define_method :name do
    puts 'Dave'
  end
end

Then, you can just type Person.new.name and it will work exactly as your class.

Checking that Person is an instance of class Class is as easy as typing in your repl Person.class and you get Class in return.



来源:https://stackoverflow.com/questions/7250523/is-class-declaration-an-eyewash-in-ruby-is-everything-really-object-oriented

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