【发布时间】:2020-07-06 20:14:49
【问题描述】:
假设我们有以下代码:
def run(input)
start = 0
lap = 0
while true
opcode = input[start]
input1 = input[start + 1]
input2 = input[start + 2]
output = input[start + 3]
if opcode == 1
input[output] = input[input1] + input[input2]
elsif opcode == 2
input[output] = input[input1] * input[input2]
elsif opcode == 99
puts "breaking"
break
else
puts "CANT RECOGNIZE THAT OPCODE"
end
start += 4
lap += 1
end
puts input
puts "finished after #{lap} loops"
end
input = [1,9,10,3,2,3,11,0,99,30,40,50]
run(input)
我明白为什么打印 input1 我得到了存储在数组 (9) 中那个位置的数字,但我不明白为什么打印 input[input1] (input[input[start + 1]]) 会访问那个位置的数字值 ( 9) 指向 (30)。
代码适用于练习,但我不明白为什么。
【问题讨论】:
-
提示:了解
case,它可以帮助您的代码更容易理解和更高效。 -
还可以考虑使用
input.each_slice(4) do |opcode, input1, input2, output|循环以分成 4 块。 -
谢谢。我实际上保存了您昨天的回复,但我让它以这样的原始方式工作,并考虑稍后对其进行重构。不过我还是不明白。
-
几乎 Ruby 中的所有内容都是解析为某个值的表达式。
input[9] == 30,所以任何解析为9的索引也将返回30,因为这是作为第九个元素存储在输入数组中的值。