liveBook · Manning

Class.new

As explained in The Well-Grounded Rubyist, Fourth Edition

Class.new is a Ruby class method that creates a class object, optionally with a specified superclass and block-defined contents.

Class.new creates a class object by sending new to Class, just as Object.new creates an object. The result can live in a local variable instead of a constant and can create instances with its own new method. section 3.6.1

Define an anonymous class with a method

c = Class.new do def say_hello puts "Hello!" end end c.new.say_hello The block runs as part of class creation, adding the say_hello instance method. The resulting class is anonymous unless you later assign it to a constant. section 3.6.1

Use Class.new when:

  • You need a class object created dynamically and held by an ordinary variable. section 3.6.1
  • You want to define instance methods immediately through a block. section 3.6.1
  • You need an alternative to the class keyword; Struct and Data instead target concise attribute-focused class creation. section 3.1.3
c = Class.new do
  def say_hello
    puts "Hello!"
  end
end

Inspect the runnable pattern for creating a class and defining an instance method in the same block. section 3.6.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains constructor equivalence and block-defined methods, while deferring practical anonymous-class applications.
Examples
Uses a local class variable, an instance created through new, and a say_hello method defined in a Class.new block.
What it assumes
Assumes familiarity with classes, objects, instances, method calls, and basic blocks.
What you can do after
Build it from scratch by creating a class object, defining methods in a block, and instantiating the result.
How it connects
Connects class objects with objects, instances, blocks, instance methods, Struct, and Data.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.