What the purpose of bind/unbind methods in Ruby?

后端 未结 1 1824
醉酒成梦
醉酒成梦 2021-02-20 12:56

What is the purpose of having Method#unbind and UnboundMethod#bind?

From what I gather, methods are callable objects like procs and lambdas, ex

相关标签:
1条回答
  • 2021-02-20 13:15

    It is indeed useful for metaprogramming. Suppose you want to know the location of the source code for SomeClass#method. If you can generate an instance of SomeClass, then you can create a (bound) method instance of it on that SomeClass instance, on which you can call various methods to investigate some meta-data of the method. But what if you did not know the method signature of SomeClass#new, or what if SomeClass's constructor method was named other than SomeClass#new? Just safely creating an instance of SomeClass can be difficult. That is where unbound method comes in handy. Without bothering with a particular instance of the class, or with how to create an instance, you can simply do SomeClass.instance_method(:a_method) (which is an unbound method), then call source_location on it to investigate the location of the definition:

    unbound = SomeClass.instance_method(:a_method)
    puts unbound.source_location
    

    And when would this kind of metaprogramming be necessary in the real world applications? One example is when you are creating an IDE with functions for method lookup.

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