gpt4 book ai didi

ruby - 创建一个绑定(bind),其唯一变量是哈希中的键

转载 作者:数据小太阳 更新时间:2023-10-29 07:37:52 25 4
gpt4 key购买 nike

我知道我可以使用 ostruct 从哈希创建绑定(bind),如下所示:

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, we want this
p eval("b", my_binding) #good, we want this
p eval("not_in_locals", my_binding) #bad, don't want it to access this, but it can

您可以在此处看到输出,这证实了代码中的注释:https://eval.in/132925

如您所见,问题在于 Binding 还绑定(bind)了局部上下文中的变量,这些变量在哈希中。我想要一种从 Hash 创建 Binding 对象的方法,除了来自该 Hash 的键之外,这些对象不绑定(bind)任何东西。

最佳答案

你可以尝试这样的事情。它绕过对辅助类方法调用的直接 eval() 调用。辅助类方法称为 evaluate(),但它仅适用于非常简单的值(目前仅测试过字符串和整数)并且依赖于 inspect()。

但是如果你正在处理的值的类型是提前知道的,你可以修改它来工作。

class HashBinding
def initialize(hash)
@hash = hash
end

def evaluate(str)
binding_code = @hash.to_a.map do |k,v|
"#{k} = #{v.inspect};"
end.join(" ")
eval "#{binding_code}; #{str}"
end
end

not_in_hash = 'I am not in the 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}"')

输出是:

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' for #<HashBinding:0x007fcc0b9ec1e8> (NameError)
from binding_of_hash.rb:10:in `eval'
from binding_of_hash.rb:10:in `evaluate'
from binding_of_hash.rb:20:in `<main>'

关于ruby - 创建一个绑定(bind),其唯一变量是哈希中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22899525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com