What are the restrictions for method names in Ruby?

前端 未结 5 1091
甜味超标
甜味超标 2020-11-27 16:03

For example, I found the method name bundler? in the following snippet, and don\'t know whether the ? character is a specialized keyword or just pa

5条回答
  •  自闭症患者
    2020-11-27 16:15

    What others say is true for the built-in syntax, however there seems to be no back-end restrictions on what can be used if you use methods like define_method + send:

    define_method(:'$% ^&') { 0 }
    define_method(:'你好') { 1 }
    
    send(:'$% ^&') == 0 or raise
    send(:'你好') == 1 or raise
    

    This fact can be useful: for example Rails' ActiveSupport::Testing::Declarative.test method uses it so as not to do complex conversions on:

    test 'Some Controller#Method' do
    

    to a saner name, which might conflict with another test named:

    test 'Some Controller_Method' do
    

    This is mentioned on the Testing Guide.

    Curiosity: a similar thing happens in Java, where the bytecode method name gives way more choice than the Java language: Why does the JVM allow us to name a function starting with a digit in bytecode?

提交回复
热议问题