-2
这是它应该响应的基本结构,但我不知道如何代码的类Interprete如何使基本的Ruby解释器
interpreta=Interprete.new
interprete.add("a=0")
interprete.add("b=1")
interprete.add("a=b+10")
interprete.execute
interprete.value("a")#11
这是它应该响应的基本结构,但我不知道如何代码的类Interprete如何使基本的Ruby解释器
interpreta=Interprete.new
interprete.add("a=0")
interprete.add("b=1")
interprete.add("a=b+10")
interprete.execute
interprete.value("a")#11
您可以使用binding。这是一种将范围'存储'到可以使用eval
随时重新打开的变量的方法。这是一个很好的教程,以及我作为参考来拼凑出一个解决方案Ruby’s Binding Class (binding objects) :
class Interprete
def initialize
@commands = []
@binding = binding
end
def add(command)
@commands.push command
end
def execute
@commands.each { |command| @binding.eval command }
@commands = []
end
def value(variable_name)
@binding.eval variable_name
end
end
用法:
i = Interprete.new
i.add "a = 1"
i.execute
i.value "a" # => 1
关于此的注解:binding
每次被称为时间返回一个新的对象;这就是为什么它被缓存在@binding
实例变量中。如果不这样做,每个命令将在不同的范围内执行,并且结果将无法访问。
非常感谢 –
你好@Rodrigo,欢迎来到StackOverflow,好像是你的作业?你尝试过什么吗? –
想要(必须)在Ruby中编写基本的解释器或基本的Ruby解释器(解释Ruby的解释器)? – Stefan
@Зелёный我不知道从哪里开始 –