Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "Class.new"?

Tags:

ruby

I don't understand the Sheep = Class.new part in the following piece of code.

module Fence 
  Sheep = Class.new do
    def speak
      "Bah."
    end
  end
end

def call_sheep
  Fence::Sheep.new.speak
end

What exactly is it doing?

like image 758
Praveen_Shukla Avatar asked Jul 21 '15 06:07

Praveen_Shukla


1 Answers

According to the documentation, Class.new

Creates a new anonymous (unnamed) class with the given superclass (or Object if no parameter is given).

Furthermore,

You can give a class a name by assigning the class object to a constant.

Sheep is that constant, so your code is equivalent to:

module Fence 
  class Sheep
    def speak
      "Bah."
    end
  end
end
like image 70
Stefan Avatar answered Sep 19 '22 12:09

Stefan