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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With