开发者

Creating Objects from objects ? Or am i deluded

开发者 https://www.devze.com 2023-04-01 21:36 出处:网络
What 开发者_运维知识库is happening in the following code A = Class.new class << A def speak

What 开发者_运维知识库is happening in the following code

A = Class.new

class << A
  def speak
    puts "Dave"
  end
end

A.speak
B = A.new 

How is this possible what is really happening. and what is 'Class' class.


A = Class.new

This is similar to:

class A
end

As you are defining an empty class and giving it the name A. (NB: In Ruby the convention is that identifiers starting with a capital letter are constants.)

class << A
  def speak
    puts "Dave"
  end
end

is similar to:

class A
  def A.speak
    puts "Dave"
  end
end

Here you are defining a class method on A (as opposed to an instance method).

The line:

A.speak

is simply calling the class method.

Finally:

B = A.new

is creating an instance of class A and assigning it to the constant B.


To answer your other question. The class of Class is... Class! You can see this in irb:

irb(main):022:0> Class.class
=> Class
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号