Ruby程序报错no implicit conversion from nil to integer,如何实现无效号码终止?
解决GSM订阅者折扣程序的无效号码终止问题
需求说明:
- 输入电话号码若在订阅者数组中,输出状态为
VALID,并根据对应折扣状态输出DISCOUNT: POSSIBLE或DISCOUNT: IMPOSSIBLE - 输入号码不在数组中,仅输出
STATUS: INVALID并终止程序
原代码问题:无效号码时未终止程序,导致starred_customer?方法接收nil索引,触发no implicit conversion from nil to integer (TypeError)错误。
修正后的完整代码
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(telephone_no) # 简化写法,直接传递匹配值给find_index end def starred_customer?(starred_customer, customer_index) if starred_customer[customer_index] puts "DISCOUNT: POSSIBLE" else puts "DISCOUNT: IMPOSSIBLE" end end telephone_no = gets.chomp customer_index = telephone_no_to_customer_index(subscribers, telephone_no) if customer_index.nil? puts "STATUS: INVALID" exit # 直接终止程序,避免后续逻辑执行 else puts "STATUS: VALID" starred_customer?(starred_customer, customer_index) end
关键修改点
- 提前终止逻辑:拿到号码索引后立即判断是否为
nil,若是则输出INVALID并调用exit终止程序,彻底避免后续错误逻辑触发 - 减少冗余操作:只调用一次
telephone_no_to_customer_index方法,复用得到的索引值,避免重复遍历数组 - 简化代码逻辑:
- 简化
telephone_no_to_customer_index方法,直接使用find_index的参数匹配能力 - 移除
starred_customer?方法中冗余的== true/false判断,直接用布尔值本身作为条件 - 删掉原代码中多余的
puts discount_state(原方法无有效返回值,会输出nil)
- 简化
内容的提问来源于stack exchange,提问作者ahailtotheKing
相关产品推荐
相关产品推荐

