Created
February 14, 2012 20:22
-
-
Save Burgestrand/1829951 to your computer and use it in GitHub Desktop.
A Ruby method that evals a string of code and returns a hash of all locals defined inside
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Eval a string of code, returning a hash of all local variables and their values. | |
# | |
# @param [String] code | |
# @param [Binding] binding | |
# @param [String] file (shows up in backtrace if an error occurs) | |
# @param [Integer] line (shows up in backtrace if an error occurs) | |
# @return [Hash] a map of :local_var => value_of_that_var | |
def eval!(__code__, binding = nil, file = __FILE__, line = (__LINE__ + 1)) | |
eval <<-SOURCE, binding, file, line | |
#{__code__} | |
local_variables.each_with_object({}) do |var, store| | |
store[var] = eval("\#{var}") | |
end | |
SOURCE | |
end | |
if $0 == __FILE__ | |
locals = eval!("hello_world = 'Hi!'") | |
locals[:hello_world] == "Hi!" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment