Actions
Bug #20637
closedSyntaxError class definition in method body can be bypassed
    Bug #20637:
    SyntaxError class definition in method body can be bypassed
  
Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 3.4.0dev (2024-07-11T06:59:45Z master a1f7432550) [x86_64-linux]
Description
Class definition in method body is prohibited in Ruby
def f
  class ::A; end # class definition in method body (SyntaxError)
  module B; end # module definition in method body (SyntaxError)
end
But it can be bypassed by using class <<
def f
  class << Object.new
    class ::A; end # Syntax OK
    module B; end # Syntax OK
  end
end
  
        
          
          Updated by zverok (Victor Shepelev) over 1 year ago
          
          
        
        
      
      As far as I understand, that’s legitimate code that works and might be useful for some metaprogramming:
def f(o)
  class << o
    class ::A; end # Syntax OK
    module B; end # Syntax OK
  end
end
o = Object.new
f(o)
o.singleton_class::B #=> #<Class:0x00007efd52a7bba0>::B
A #=> A
        
          
          Updated by tompng (tomoya ishida) over 1 year ago
          
          
        
        
      
      dynamic constant assignment (SyntaxError) can be also bypassed
def f
  class << Object.new
    ::A = 1
  end
end
        
          
          Updated by matz (Yukihiro Matsumoto) over 1 year ago
          
          
        
        
      
      Hmm, I think I'd let them unchanged. I don't think it's worth prohibiting constant definition in singleton class definitions.
Matz.
        
          
          Updated by matz (Yukihiro Matsumoto) over 1 year ago
          
          
        
        
      
      - Status changed from Open to Closed
 
Actions