如何在Ruby中创建/提取变量/哈希到当前绑定中?

如何在Ruby中创建/提取变量/哈希到当前绑定中?,ruby,variables,binding,hash,extract,Ruby,Variables,Binding,Hash,Extract,如何在Ruby中创建/提取变量/哈希到当前绑定中? 例如,以下情况会导致名称错误: class Hash def extract(b) self.each do |key, value| bind = b.eval <<-END #{key} = nil proc { |value| #{key} = value } END bind.call(value) end end end hash

如何在Ruby中创建/提取变量/哈希到当前绑定中? 例如,以下情况会导致
名称错误

class Hash
  def extract(b)
    self.each do |key, value|
      bind = b.eval <<-END
        #{key} = nil
        proc { |value| #{key} = value }
      END
      bind.call(value)
    end
  end
end

hash = {:a => 1}
hash.extract(binding)
puts a
我不确定在将当前绑定传递给方法(例如,
#export#u to
,如下)之后,如何使局部变量出现在调用方的执行上下文中。但也可以做一些类似的事情,表面上达到同样的效果:

class Hash
  def export_to(o)
    each do |key, value|
      o.define_singleton_method(key) { value }
    end
  end
end

hash = {:a => 1}
hash.export_to self
puts a
请注意,传递的是
self
,而不是
binding

还请注意,这里的一个常见模式是设置实例变量而不是方法,在这种情况下,
put
和以后的代码现在可以引用
@a

class Hash
  def export_to(o)
    each do |key, value|
      o.define_singleton_method(key) { value }
    end
  end
end

hash = {:a => 1}
hash.export_to self
puts a