Can I create Ruby classes within functions bodies ? I seem to be getting error which tells me its not allowed but I think it should be as classes are too objects here.
class A def method class B end end end
This fails with error 'class definition inside method body. If we cant, why cant we create classes inside methods ?
Classes in Ruby are first-class objects—each is an instance of class Class . When a new class is created, an object of type Class is initialized and assigned to a global constant ( Name in this case). Classes, modules, and objects are interrelated.
In short: no, Ruby does not support nested methods.
Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition. By default, methods are marked as public which is defined in the class definition.
In Ruby, a method provides functionality to an Object. A class method provides functionality to a class itself, while an instance method provides functionality to one instance of a class. We cannot call an instance method on the class itself, and we cannot directly call a class method on an instance.
you can create classes, but you cannot assign constants from inside a method.
this example works:
class A
def a
b = Class.new
def b.xxx
"XXX"
end
b
end
end
a = A.new.a
p a # #<Class:0x7fa74fe6cc58>
p a.xxx # "XXX"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With