我有一些代码在数组中查找关键字(线索)并返回其位置,我试图获取此结果并将其作为puts命令执行。这种搜索是必要的,因为我不会总是知道数组中的“软件包含”位置
我的代码下面只是简单的输出“线索[2]”但我想实际执行put clues [2],好像我输入了它所以我的输出将是“软件包含”。
有没有办法让这个可行?
clues = Array.new
clues << 'Power supply type'
clues << 'Slots'
clues << 'Software included'
Var100 = clues.rindex('Software included')
Var101 = "clues[#{Var100}]"
command_store = Array.new
command_store << lambda {puts "clues[#{Var101}]" }
答案 0 :(得分:2)
你太复杂了。例如,lambda中的puts
命令等同于:
puts "clues[clues[2]]"
通过一点调试打印,您将能够使其正常工作。这是我想你想得到的:
clues = ['Power supply type', 'Slots', 'Software included']
command_store = []
command_store << lambda {
idx = clues.rindex('Software included')
puts clues[idx]
}
command_store.each(&:call) # call every lambda in the array
# >> Software included
虽然这个确切的代码对我没有任何意义(只有使用该索引来打印值才获得值的索引),但我知道它可能是一个过于简化的示例。
[]
添加到Array.new
。