Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Objects from objects ? Or am i deluded

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.

like image 932
pankajdoharey Avatar asked Jun 05 '26 05:06

pankajdoharey


1 Answers

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
like image 87
Mike Tunnicliffe Avatar answered Jun 06 '26 22:06

Mike Tunnicliffe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!