我想连接两个过程的主体。但不像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 编辑,但是 assignment
和 printing
procs在定义它们的地方的上下文中进行评估。
我想拆分原始过程的原因是我可以 DRY 我的测试。
最佳答案
你可以做到
combined = proc {
instance_eval &assignment
instance_eval &printing
}
但如果有人想出更惯用的东西,我不会感到惊讶
关于ruby - 连接 proc,同时保留上下文重新评估功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33847604/