Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

class method

Class.new

Class.new(super_class=Object) → a_class
Class.new(super_class=Object) { |mod| ... } → a_class

Creates a new anonymous (unnamed) class with the given superclass (or Object if no parameter is given). You can give a class a name by assigning the class object to a constant.

If a block is given, it is passed the class object, and the block is evaluated in the context of this class like class_eval.

Example
fred = Class.new do
  def meth1
    "hello"
  end
  def meth2
    "bye"
  end
end

a = fred.new     #=> #<#<Class:0x100381890>:0x100376b98>
a.meth1          #=> "hello"
a.meth2          #=> "bye"

Assign the class to a constant (name starting uppercase) if you want to treat it like a regular class.

See also #new #allocate #attached_object also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0