-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
@Зелёный我不知道從哪裏開始 –