没有从nil到整数的隐式转换(TypeError):我如何跳过此错误?



我正在写一个与GSM可能的折扣和用户关系相关的程序。如果给定的电话号码在用户数组中,那么它也有一个可能的折扣状态…如果为真,那么它可以有折扣,否则不能(假)。如果电话号码碰巧不在订阅者数组中,那么程序应该在最后给出一条消息时停止:"STATUS: invalidate ">

subscribers = %w[5553457867 5417890987 5524567867 5356789865 5321234567 5546754321 5389876543]
starred_customer = [true, false, true, true, false, false, true]
def telephone_no_to_customer_index(subscribers, telephone_no) 
subscribers.find_index do |number|
telephone_no == number 
end 
end
def starred_customer?(starred_customer, customer_index)  
x = starred_customer[customer_index]
if x == true
puts "DISCOUNT: POSSIBLE"
elsif x == false
puts "DISCOUNT: IMPOSSIBLE"
end
end
telephone_no = gets.chomp 
state = telephone_no_to_customer_index(subscribers, telephone_no)
state ? (puts "STATUS: VALID") : (puts "STATUS: INVALID")  #should i write here && (return)? 
customer_index = telephone_no_to_customer_index(subscribers, telephone_no)
discount_state = starred_customer?(starred_customer, customer_index)
puts discount_state

一旦输入的电话号码不在订阅者数组中,程序就应该跳过其他所有内容。由于程序没有停止,它传递了"nil"作为第二个方法的参数,由于第二个方法不能将折扣状态应用于nil,它会给出一个错误:没有从nil到整数的隐式转换(TypeError):

我想从程序中返回"STATUS: invalidate "如果telephone_no不是订阅者数组的元素,则停止。

如果您想在特定条件下退出程序,您可以这样做。

if not state
puts "STATUS: INVALID"
exit 
end
puts "STATUS: VALID"
customer_index = telephone_no_to_customer_index(subscribers, telephone_no)
discount_state = starred_customer?(starred_customer, customer_index)
puts discount_state

你也可以使用unless:

unless state
puts "STATUS: INVALID"
exit 
end

最新更新