5

In Ruby, you can easily access local variables programmatically by using local_variables and eval. I would really like to have meta-programming access to these variables using a single method call such as

# define a variable in this scope, such as
x = 5
Foo.explore_locals  # inside the Foo#explore_locals method, access x

where Foo is some external module. The idea is to display and export local variables in a nice way.

What should be inside the explore_locals method? Is there any way to make this possible? If absolutely necessary, I guess it could be

Foo.explore_locals binding

but this is much less elegant for the application I have in mind.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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, :_]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.