gpt4 book ai didi

ruby - 连接 proc,同时保留上下文重新评估功能

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

我想连接两个过程的主体。但不像here , 有一个扭曲。生成的过程应该保留原始过程的instance_eval能力。

这听起来可能有点令人困惑,所以这是我的用例。


我正在用 Ruby 实现另一种语言作为内部 DSL。过于简化的实现:

class Interpreter
def self.run(&program)
Interpreter.new.instance_eval(&program)
end

def initialize
@variables = {}
end

def assign_variable(name, value)
@variables[name] = value
end

def display(name)
puts @variables[name]
end
end

Interpreter.run do
assign_variable :foo, 42
display :foo
end

如果我将 proc 的主体分成另外两个:

assignment = proc { assign_variable :foo, 42 }
printing = proc { display :foo }
combined = proc { assignment.call; printing.call }

Interpreter.run(&combined)

它不会工作,因为 combined proc 正在被 instance_eval 编辑,但是 assignmentprinting procs在定义它们的地方的上下文中进行评估。

我想拆分原始过程的原因是我可以 DRY 我的测试。

最佳答案

你可以做到

combined = proc {
instance_eval &assignment
instance_eval &printing
}

但如果有人想出更惯用的东西,我不会感到惊讶

关于ruby - 连接 proc,同时保留上下文重新评估功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33847604/

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