What is the "Class.new"?

I do not understand the part Sheep = Class.newin the following code fragment.

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

def call_sheep
  Fence::Sheep.new.speak
end

What exactly is he doing?

+4
source share
2 answers

In accordance with the documentation Class.new

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

Besides,

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

Sheep is a constant, so your code is equivalent:

module Fence 
  class Sheep
    def speak
      "Bah."
    end
  end
end
+9
source
Sheep = Class.new do
  def speak
    "Bah."
  end
end

Class.new is the syntax for defining classes in Ruby. The above codes are similar to the following:

class Sheep
  def speak
    "Bah."
  end
end
+3
source

Source: https://habr.com/ru/post/1598820/


All Articles