ruby - Create a Binding whose only variables are keys from a Hash -
i know can create binding hash using ostruct
, this:
require 'ostruct' not_in_locals = "we don't want this" locals = {a: 1, b: 2} my_binding = openstruct.new(locals).instance_eval { binding } p my_binding p eval("a", my_binding) #good, want p eval("b", my_binding) #good, want p eval("not_in_locals", my_binding) #bad, don't want access this, can
you can see output here, confirms comments in code: https://eval.in/132925
as can see, problem binding binds variables in local context not in hash. i'd method creating binding objects hash, bound nothing besides keys hash.
you try this. bypasses straight eval() call helper class method call. helper class method called evaluate(), works simple values (only strings , integers tested far) , relies on inspect().
but if types of values dealing known ahead of time, modify work.
class hashbinding def initialize(hash) @hash = hash end def evaluate(str) binding_code = @hash.to_a.map |k,v| "#{k} = #{v.inspect};" end.join(" ") eval "#{binding_code}; #{str}" end end not_in_hash = 'i not in hash' hash = { :foo => 'foo value', :baz => 42} hash_binding = hashbinding.new(hash) hash_binding.evaluate('puts "foo = #{foo}"') hash_binding.evaluate('puts "baz = #{baz}"') hash_binding.evaluate('puts "not_in_hash = #{not_in_hash}"')
the output is:
ruby binding_of_hash.rb foo = foo value baz = 42 binding_of_hash.rb:10:in `eval': undefined local variable or method `not_in_hash' #<hashbinding:0x007fcc0b9ec1e8> (nameerror) binding_of_hash.rb:10:in `eval' binding_of_hash.rb:10:in `evaluate' binding_of_hash.rb:20:in `<main>'
Comments
Post a Comment