如何在Ruby数组中解析并切换active字段的取值?
修正Ruby数组元素切换的代码问题
原代码存在两个关键问题:
- 使用
each遍历时,lists = ...只是修改了局部变量,不会同步更新原数组的元素 - 第二个判断条件错误地调用了数组的
list.include?,应该检查当前元素lists,且逻辑可以简化
方案一:使用map!直接修改原数组
map!会遍历数组并替换每个元素,直接修改原数组:
list = ["beam=0", "active=0", "rate=11", "version=4.1", "delay=5"] list.map! do |item| if item.start_with?("active=") item == "active=0" ? "active=1" : "active=0" else item end end
方案二:通过索引定位修改
先找到"active"项的索引,再直接修改对应元素:
list = ["beam=0", "active=0", "rate=11", "version=4.1", "delay=5"] active_index = list.find_index { |item| item.start_with?("active=") } if active_index list[active_index] = list[active_index] == "active=0" ? "active=1" : "active=0" end
方案三:使用each_with_index遍历修改
通过索引直接操作原数组元素:
list = ["beam=0", "active=0", "rate=11", "version=4.1", "delay=5"] list.each_with_index do |item, idx| if item == "active=0" list[idx] = "active=1" elsif item == "active=1" list[idx] = "active=0" end end
以上三种方案都能实现需求:当数组中是active=0时切换为active=1,反之则切换为active=0,其他元素保持不变。
内容的提问来源于stack exchange,提问作者Rubin
相关产品推荐
相关产品推荐

