I’m having a little problem with this Ruby code:
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 is an array that consists of Hashes.
For some reason, after choosing the right TAP i can access correct bestuserlevel value, but no besttap (I suppose to have a certain hash there…)
Can anyone please help me sort this out?
This code works fine when I run it. Though I’m assuming those that “+ l” is a “+ 1” here. Perhaps that is your problem?
Other than that typo, this seems to work correctly, so I’m assuming the problem is somewhere in your taps Hash – If you set a static hash with values as a test, does it still break?
I should add that besttap will obviously be empty in any situation where the besttap.replace is not triggered, so that would be where I would look – maybe your input hash doesn’t have any values that trigger the replace?
(In which case bestuserlevel would still have a value)