Class.new lets you create a new class on the fly without naming it right away. This helps when you want a quick, custom class without writing a full class definition.
0
0
Class.new for dynamic class creation in Ruby
Introduction
When you need a simple class for a one-time use.
When you want to create many similar classes dynamically.
When you want to add methods or behavior to a class quickly.
When you want to avoid cluttering your code with many class names.
When experimenting or testing small pieces of code.
Syntax
Ruby
my_class = Class.new(superclass = Object) do # methods and definitions here end
You can pass a superclass to inherit from, or leave it blank to inherit from Object.
The block defines methods and behavior inside the new class.
Examples
This creates a new class named MyClass with a method greet that returns "Hello!".
Ruby
MyClass = Class.new do def greet "Hello!" end end
Here, Dog inherits from Animal and overrides the speak method.
Ruby
Animal = Class.new do def speak "..." end end Dog = Class.new(Animal) do def speak "Woof!" end end
This creates an unnamed class, makes an object, and calls its method.
Ruby
anonymous = Class.new do def info "I am anonymous" end end obj = anonymous.new puts obj.info
Sample Program
This program creates a Greeter class dynamically with a greet method. Then it creates an object and prints a greeting.
Ruby
Greeter = Class.new do def greet(name) "Hello, #{name}!" end end g = Greeter.new puts g.greet("Alice")
OutputSuccess
Important Notes
You can assign the new class to a constant to use it later by name.
Classes created this way behave like normal classes.
Use this technique to keep your code flexible and DRY (Don't Repeat Yourself).
Summary
Class.new creates a new class dynamically.
You can add methods inside the block.
It helps make quick, custom classes without writing full class definitions.