Are there equivalents to Ruby's method_missing in other languages?

前端 未结 15 1627
渐次进展
渐次进展 2020-12-08 08:00

In Ruby, objects have a handy method called method_missing which allows one to handle method calls for methods that have not even been (explicitly) defined:

相关标签:
15条回答
  • 2020-12-08 08:50

    Actionscript 3.0 has a Proxy class that can be extended to provide this functionality.

    dynamic class MyProxy extends Proxy {
      flash_proxy override function callProperty(name:*, ...rest):* {
        try {
          // custom code here
        }
        catch (e:Error) {
          // respond to error here
        }
    }  
    
    0 讨论(0)
  • 2020-12-08 08:50

    Its equivalent in Io is using the forward method.

    From the docs:

    If an object doesn't respond to a message, it will invoke its "forward" method if it has one....

    Here is a simple example:

    Shout := Object clone do (
        forward := method (
            method_missing := call message name
            method_missing asUppercase
        )
    )
    
    Shout baz println     # => BAZ
    

    /I3az/

    0 讨论(0)
  • 2020-12-08 08:51

    I was looking for this before, and found a useful list (quickly being overtaken here) as part of the Merd project on SourceForge.


     Construct                          Language
    -----------                        ----------
     AUTOLOAD                           Perl
     AUTOSCALAR, AUTOMETH, AUTOLOAD...  Perl6
     __getattr__                        Python
     method_missing                     Ruby
     doesNotUnderstand                  Smalltalk
     __noSuchMethod__(17)               CoffeeScript, JavaScript
     unknown                            Tcl
     no-applicable-method               Common Lisp
     doesNotRecognizeSelector           Objective-C
     TryInvokeMember(18)                C#
     match [name, args] { ... }         E
     the predicate fail                 Prolog
     forward                            Io
    

    With footnotes:

    • (17) firefox
    • (18) C# 4, only for "dynamic" objects
    0 讨论(0)
  • 2020-12-08 08:53

    Smalltalk has the doesNotUnderstand message, which is probably the original implementation of this idea, given that Smalltalk is one of Ruby's parents. The default implementation displays an error window, but it can be overridden to do something more interesting.

    0 讨论(0)
  • 2020-12-08 08:53

    This is accomplished in Lua by setting the __index key of a metatable.

    t = {}
    meta = {__index = function(_, idx) return function() print(idx) end end}
    setmetatable(t, meta)
    
    t.foo()
    t.bar()
    

    This code will output:

    foo
    bar
    
    0 讨论(0)
  • 2020-12-08 08:57

    Tcl has something similar. Any time you call any command that can't be found, the procedure unknown will be called. While it's not something you normally use, it can be handy at times.

    0 讨论(0)
提交回复
热议问题