What are the restrictions for method names in Ruby?

前端 未结 5 1105
甜味超标
甜味超标 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:14

    To add one thing: you can also tell an object to run a method with no name at all and it will try to invoke a method named call:

    #!/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
    

    There is not actually any method named call defined on Object, but there is one on the Method and Proc classes.

    In some languages () is an operator for function invocation, and that seems pretty similar to what's happening here.

    This is used e.g. in Rails' JBuilder:

    https://github.com/rails/jbuilder

    It is documented on page 196 of the O'Reilly Ruby book:

    Ruby 1.9 offers an additional way to invoke a Proc object; as an alternative to square brackets, you can use parentheses prefixed with a period:

    z = f.(x,y)
    

    .() looks like a method invocation missing the method name. This is not an operator that can be defined, but rather is syntactic-sugar that invokes the call method. It can be used with any object that defines a call method and is not limited to Proc objects.

提交回复
热议问题