我对这个Ruby代码有点问题:
class Tap
attr_accessor :c, :v, :n, :tname
def initialize(n, c, v)
@c = c.to_i
@v = v.to_f
@n = n.to_i
@tname = sprintf("T-%d%02d DS", @n, @c)
end
end
#...
taps = Array.new
File.open("taps.txt").each { |line|
n, c, v = line.split("\t")
tap = Tap.new(n, c, v)
taps.push tap
}
besttap = Tap.new(100,100,100) # Here I try to create a global varialble
2.upto(floors) { |f|
l += cable_loss * floor_height
out << "some text to output"
bestuserlevel = 10
besttap = Tap.new(100,100,100)
taps.each { |tap|
l_in_tmp = tap.v + l
userlevel = l_in_tmp - tap.c
if userlevel.abs < bestuserlevel.abs
besttap = tap
bestuserlevel = userlevel
end
puts tap.inspect
}
l += besttap.v #WELL, I CANNOT ACCESS besttap here. I get that one created with Tap.new(100,100,100), but I need one chosen by the cycle before (it should be something Tap.new(2, 8,0.5) - i.e - best suitable value from taps array )...
out << "some text to output"
}
taps
是一个由哈希组成的数组。
出于某种原因,在选择正确的TAP后,我可以访问正确的bestuserlevel
值,但没有besttap
(我想在那里有一定的哈希值)
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:1)
当我运行它时,此代码工作正常。虽然我假设那些“+ l”在这里是“+ 1”。也许那是你的问题?
除了那个拼写错误之外,这似乎工作正常,所以我假设问题出在你的点击哈希的某个地方 - 如果你设置一个静态哈希值作为测试,它仍然会破坏吗?
我应该补充一点,在任何没有触发besttap.replace的情况下,besttap显然都是空的,所以这就是我要看的地方 - 也许你的输入哈希没有任何触发替换的值?
(在这种情况下,bestuserlevel仍然有值)