Ruby中的方法名有哪些限制?

Ruby中的方法名有哪些限制?,ruby,Ruby,例如,我在下面的代码片段中找到了方法名bundler?,不知道?字符是专用关键字还是方法名的一部分 # This is a predicate useful for the doc:guides task of applications. def bundler? # Note that rake sets the cwd to the one that contains the Rakefile # being executed. File.exists?('Gemfile') e

例如,我在下面的代码片段中找到了方法名
bundler?
,不知道
字符是专用关键字还是方法名的一部分

# This is a predicate useful for the doc:guides task of applications.
def bundler?
  # Note that rake sets the cwd to the one that contains the Rakefile
  # being executed.
  File.exists?('Gemfile')
end

允许的字符有:
a-Z、
0-9
,只要不在开头、
、和
(对于布尔函数)和
(用于破坏性函数)和
=
(用于setter)。

方法名称可以以
结尾
=
。也允许使用下划线。除此之外,还有一些看起来像运算符的方法(例如,
+
*
>
[]
),您可以为自己的类定义这些方法

Ruby中的方法名称可能包含大写和小写字母、数字、下划线
\uu
和点号
=

方法名称不能以数字开头,字符
=
只能出现在末尾

方法名称中可以使用非ASCII字符,但这可能会导致非常混乱的情况,不应该是常见的做法

在Ruby中,以小写字符开头的方法名是一种很好的做法,尽管不是强制性的,因为以大写字母开头的名称是常量。仍然可以为方法使用常量名称,但如果没有括号,您将无法调用它,因为interpeter将查找作为常量的名称:

def Capital
    nil
end

Capital    # NameError: uninitialized constant Capital
Capital()  # => nil
在定义方法名称时,一些非常广泛且一致使用的约定是:

  • 方法名称是完全小写的,带有下划线
    作为名称中单词的分隔符(例如
    数学::sqrt
    数组#每个_索引
    ,…)

  • 谓词的最后一个字符是问号
    (例如
    数组#空?
    散列#有u键?
    ,…)。虽然谓词通常返回布尔值,但情况并非总是如此:如果谓词的计算结果为false,则这些方法只需返回
    nil
    false
    ,否则返回任何其他值(例如,
    File::size?
    返回
    nil
    如果文件不存在,则文件大小为
    整数

  • 修改被调用对象的状态或具有异常行为的方法的最后一个字符是感叹号
    ;这些方法有时被称为mutators,因为它们通常是其他方法的破坏性或就地版本(例如,
    Array#sort!
    Array#slice!
    ,…)

  • setter具有一个等号
    =
    作为最后一个字符(例如,
    数组#[]=
    ,…);Ruby interpeter为调用setter方法提供语法糖:

    a = [4, 5, 6]
    a[0] = 3    # Shorthand for a.[]=(0, 3)
    
  • Ruby还允许使用运算符符号作为方法名定义运算符:

    ╔═══════════════════════════╦═════════════════════════════════════════════╦═══════╗
    ║ Operators (by precedence) ║                 Operations                  ║ Arity ║
    ╠═══════════════════════════╬═════════════════════════════════════════════╬═══════╣
    ║ ! ~ +                     ║ Boolean NOT, bitwise complement, unary plus ║     1 ║
    ║                           ║ (define with method name +@, Ruby 1.9+)     ║       ║
    ║                           ║                                             ║       ║
    ║ **                        ║ Exponentiation                              ║     2 ║
    ║                           ║                                             ║       ║
    ║ -                         ║ Unary minus (define with method name -@)    ║     1 ║
    ║                           ║                                             ║       ║
    ║ * / %                     ║ Multiplication, division, modulo            ║     2 ║
    ║                           ║                                             ║       ║
    ║ + -                       ║ Addition, subtraction                       ║     2 ║
    ║                           ║                                             ║       ║
    ║ << >>                     ║ Bitwise shift                               ║     2 ║
    ║                           ║                                             ║       ║
    ║ &                         ║ Bitwise AND                                 ║     2 ║
    ║                           ║                                             ║       ║
    ║ | ^                       ║ Bitwise OR, Bitwise XOR                     ║     2 ║
    ║                           ║                                             ║       ║
    ║ < <= => >                 ║ Ordering                                    ║     2 ║
    ║                           ║                                             ║       ║
    ║ == === != =~ !~ <=>       ║ Equality, pattern matching, comparison      ║     2 ║
    ╚═══════════════════════════╩═════════════════════════════════════════════╩═══════╝
    
    ╔═══════════════════════════╦═════════════════════════════════════════════╦═══════╗
    ║ 运算符(按优先级)║                 操作║ 一致性║
    ╠═══════════════════════════╬═════════════════════════════════════════════╬═══════╣
    ║ ! ~ +                     ║ 布尔NOT、按位补码、一元加号║     1.║
    ║                           ║ (使用方法名+@,Ruby 1.9+定义)║       ║
    ║                           ║                                             ║       ║
    ║ **                        ║ 指数化║     2.║
    ║                           ║                                             ║       ║
    ║ -                         ║ 一元减号(使用方法名-@定义)║     1.║
    ║                           ║                                             ║       ║
    ║ * / %                     ║ 乘、除、模║     2.║
    ║                           ║                                             ║       ║
    ║ + -                       ║ 加减法║     2.║
    ║                           ║                                             ║       ║
    ║ >                     ║ 位移位║     2.║
    ║                           ║                                             ║       ║
    ║ &                         ║ 按位和║     2.║
    ║                           ║                                             ║       ║
    ║ | ^                       ║ 按位或,按位异或║     2.║
    ║                           ║                                             ║       ║
    ║ <  >                 ║ 订购║     2.║
    ║                           ║                                             ║       ║
    ║ == === != =~ !~        ║ 相等、模式匹配、比较║     2.║
    ╚═══════════════════════════╩═════════════════════════════════════════════╩═══════╝
    
    一元运算符方法不传递任何参数;二元运算符方法传递一个参数,并对其和
    self
    进行操作

    严格遵守运算符的算术性很重要;虽然可以使用不同的算术性定义运算符方法
    define_method(:'$% ^&') { 0 }
    define_method(:'你好') { 1 }
    
    send(:'$% ^&') == 0 or raise
    send(:'你好') == 1 or raise
    
    test 'Some Controller#Method' do
    
    test 'Some Controller_Method' do
    
    #!/usr/bin/env ruby
    
    class Foo
    
    =begin
      def call(*args)
        puts "received call with #{args.join(' ')}"
      end
    =end
    
      def method_missing(m, *args, &block)
        puts "received method_missing on `#{m}(#{args.join(', ')})`"
      end
    
    end
    
    f = Foo.new
    f.('hi')             # Not a syntax error! method_missing with m of :call
    f.send :'', 'hmm'    # method_missing with m set to :''
    f.send nil, 'bye'    # raises an error
    
    z = f.(x,y)