The method below should select a flask from a chemical system based on specific requirements and markings.
def choose_flask(requirements, flask_types, markings)
waste_min = Array.new(flask_types, Float::INFINITY)
markings.each_with_index do |marks, idx|
total_waste = 0
valid = true
requirements.each do |req|
mark = marks.find { |m| m >= req }
if mark.nil?
valid = false
break
end
waste = mark - req
total_waste += waste
end
if valid && total_waste < waste_min[idx]
waste_min[idx] = total_waste
end
end
min_value = waste_min.min
min_value == Float::INFINITY ? -1 : waste_min.index(min_value)
end
But when I run the code test, I get this error
`<': comparison of Integer with nil failed (ArgumentError)
if valid && total_waste < waste_min[idx]
^^^^^^^^^^^^^^
Can someone help me?
Looks like length of waste_min
is lower than length of markings
, this is why sometimes waste_min[idx]
returns nil, or some element of flask_types is nil.
Solution
if valid && (waste_min[idx].nil? || total_waste < waste_min[idx])
waste_min[idx] = total_waste
end