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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is similar to:
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.)is similar to:
Here you are defining a class method on
A(as opposed to an instance method).The line:
is simply calling the class method.
Finally:
is creating an instance of class
Aand assigning it to the constantB.To answer your other question. The class of
Classis…Class! You can see this inirb: