Project

General

Profile

Actions

Bug #20637

closed

SyntaxError class definition in method body can be bypassed

Added by tompng (tomoya ishida) 4 months ago. Updated 4 months ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 3.4.0dev (2024-07-11T06:59:45Z master a1f7432550) [x86_64-linux]
[ruby-core:118616]

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) 4 months 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) 4 months ago

dynamic constant assignment (SyntaxError) can be also bypassed

def f
  class << Object.new
    ::A = 1
  end
end

Updated by matz (Yukihiro Matsumoto) 4 months ago

Hmm, I think I'd let them unchanged. I don't think it's worth prohibiting constant definition in singleton class definitions.

Matz.

Actions #4

Updated by matz (Yukihiro Matsumoto) 4 months ago

  • Status changed from Open to Closed
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0