Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cant there be classes inside methods in Ruby?

Tags:

ruby

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 ?

like image 462
Nikhil Garg Avatar asked Jul 07 '10 11:07

Nikhil Garg


People also ask

Are there classes in Ruby?

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.

Can you call a method inside a method Ruby?

In short: no, Ruby does not support nested methods.

What is a class method in Ruby?

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.

What is the difference between class method and instance method in Ruby?

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.


1 Answers

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"
like image 75
zed_0xff Avatar answered Oct 11 '22 17:10

zed_0xff