Is Class declaration an eyewash in ruby? Is everyt

2020-04-14 07:52发布

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.

2条回答
可以哭但决不认输i
2楼-- · 2020-04-14 08:16

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.

查看更多
不美不萌又怎样
3楼-- · 2020-04-14 08:24

Yes, Ruby classes are objects:

>> String.is_a? Object
=> true
>> String.methods.count
=> 131
>> Fixnum.methods.count
=> 128
查看更多
登录 后发表回答