Skip to content

Instantly share code, notes, and snippets.

@tadd
Last active August 29, 2015 14:02
Show Gist options
  • Save tadd/6617023389ac5dfd0d0c to your computer and use it in GitHub Desktop.
Save tadd/6617023389ac5dfd0d0c to your computer and use it in GitHub Desktop.
abusing of local_variable_get
require './variable_table_of_caller'
def easy_printf(template)
keys = template.scan(/%{(.+?)}/).flatten.map(&:to_sym)
printf(template, variable_table_of_caller_with_level(2, *keys))
end
if $0 == __FILE__
foo = 1
bar = 'baz'
# normal:
# printf("%{foo}, %{bar}\n", foo: foo, bar: bar)
easy_printf("%{foo}, %{bar}\n") #=> 1, baz
end
require 'binding_of_caller'
def variable_table_of_caller_with_level(level, *names)
bind = binding.of_caller(level)
names.map do |name|
[name, bind.local_variable_get(name)]
end.to_h
end
def variable_table_of_caller(*names)
variable_table_of_caller_with_level(2, *names)
end
if $0 == __FILE__
x = 1
foo = 'bar'
o = Object.new
p variable_table_of_caller(*%i[x foo o]) #=> {:x=>1, :foo=>"bar", :o=>#<Object:0x00000001ead188>}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment