Access local variables from a different binding in Ruby

后端 未结 2 1558
一向
一向 2021-01-19 13:07

In Ruby, you can easily access local variables programmatically by using local_variables and eval. I would really like to have meta-programming acc

相关标签:
2条回答
  • 2021-01-19 13:41

    It's a shame there isn't a built-in way to get the caller's binding. The block trick seems to be the usual answer to this question.

    However there is another 'trick' which existed for older 1.8 Ruby versions called binding_of_caller. Looks like quix ported it to 1.9. You might want to check that out:

    https://github.com/quix/binding_of_caller

    0 讨论(0)
  • 2021-01-19 13:43

    Here is an example (but it requires extra braces {} which I would rather avoid if possible):

    module Foo
      def self.explore_locals &block
        p block.binding.eval 'local_variables'
      end
    end
    
    local_1 = 3
    Foo.explore_locals{}  # shows [:local_1, :_]
    
    0 讨论(0)
提交回复
热议问题