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
