Dynamic method calling in Ruby

后端 未结 5 743

As far as I am aware there are three ways to dynamically call a method in Ruby:

Method 1:

s = SomeObject.new
method = s.method(:dynamic_method)
metho         


        
5条回答
  •  一生所求
    2020-12-12 20:15

    Think of it this way:

    Method 1 (method.call): Single run-time

    If you run Ruby once on your program straight through, you control the entire system and you can hold onto a "pointer to your method" via the "method.call" approach. All you are doing is holding on to a handle to "live code" that you can run whenever you want. This is basically as fast as calling the method directly from within the object (but it is not as fast as using object.send - see benchmarks in other answers).

    Method 2 (object.send): Persist name of method to database

    But what if you want to store the name of the method you want to call in a database and in a future application you want to call that method name by looking it up in the database? Then you would use the second approach, which causes ruby to call an arbitrary method name using your second "s.send(:dynamic_method)" approach.

    Method 3 (eval): Self-modifying method code

    What if you want to write/modify/persist code to a database in a way that will run the method as brand new code? You might periodically modify the code written to the database and want it to run as new code each time. In this (very unusual case) you would want to use your third approach, which allows you to write your method code out as a string, load it back in at some later date, and run it in its entirety.

    For what it's worth, generally it is regarded in the Ruby world as bad form to use Eval (method 3) except in very, very esoteric and rare cases. So you should really stick with methods 1 and 2 for almost all problems you encounter.

提交回复
热议问题