【问题标题】:Parsing element in a ruby array解析 ruby​​ 数组中的元素
【发布时间】:2022-11-29 20:14:12
【问题描述】:

我喜欢解析字符串数组并更新值,例如我所拥有的:

list= ["beam=0", "active=0", "rate=11", "version=4.1", "delay=5"]

在上面的列表中我想搜索“active”并编辑它的值,比如如果“active=0”我想让它成为“active=1”,如果它的“active=1”我想让它成为“active” =0”。

What i am doing is , but its not correct ,, can someone assist in this:

list.each do |lists|
   if lists.include?("active=0")
      lists = "active=1"
   elsif list.include?("active=1")
      lists = "active=0"
   end
end

如果列表包含 active=0 ,我最终期望的是 output list = ["beam=0", "active=1", "rate=11", "version=4.1", "delay=5"] 如果list 包含 active=1,然后输出 list = ["beam=0", "active=0", "rate=11", "version=4.1", "delay=5"]

【问题讨论】:

  • 为什么不使用散列,例如hash = { beam: 0, active: 0, rate: 11, version: "4.1", delay: 5 }。这样你就可以通过hash[:active] = 1更新。

标签: ruby list parsing


【解决方案1】:

如果你可以使用散列,它更适合这个任务。

如果你不能,那么你的代码的问题是你没有更新原始值。您只是在更新 #each 迭代器中使用的变量。

做你想做的一种方法是:

list = ["beam=0", "active=0", "rate=11", "version=4.1", "delay=5"]

# convert to hash
hash = list.to_h { |x| x.split '=' }

# update any hash value
hash['active'] = hash['active'] == '0' ? '1' : '0'

# convert back to array
result = hash.map { |x| x.join '=' }

而且,如果出于某种原因,您希望尽可能接近原始代码,那么您可以使用 map 而不是 each。我不建议在这种情况下使用以下代码,因为这不是好的编码,但如果您有自己的理由并且这仅用于教育目的:

list = ["beam=0", "active=0", "rate=11", "version=4.1", "delay=5"]
result = list.map do |item|
  case item
  when 'active=0' then 'active=1'
  when 'active=1' then 'active=0'
  else
    item
  end
end

【讨论】:

  • 我收到此错误,我使用的是 ruby​​ 版本 2.7.5,“失败/错误:hash = lines.to_h { |x| x.split '=' } ArgumentError:错误的数组长度为 84(预期为 2,为 3) “
  • @Abr 那是因为其中一个字符串包含多个=。您可以通过x.split('=', 2)split限制为2个子字符串
  • 我看到一些字符串包含 "name=sit::sit_id::" 、 "IP=192.165.0.1" 和 "test=nt1,nt2," ,这是触发错误吗?错误:失败/错误:hash = lines.to_h { |x| x.split('=', 2)} NoMethodError: undefined method `to_h' for #<String:0x0000557634649538> 你是说吗? to_f to_r to_i to_s to_d to_c
  • @Abr ArgumentError 是由包含两个 = 字符的字符串引起的。它是数组索引 84 处的元素。另一个NoMethodError 与该问题无关。这是因为您(不小心)在字符串上调用了to_h
  • 好的,我明白了,我改变了限制,但似乎其中一个字符串甚至不包含“=”,你如何处理这个?失败/错误:hash = lines.to_h { |x| x.split('=', 2) } ArgumentError:93 处的数组长度错误(预期为 2,实际为 0)
【解决方案2】:

您可以遍历 list 并替换 active= 之后的数字,如下所示:

list= ["beam=0", "active=0", "rate=11", "version=4.1", "delay=5"]

list.each_with_index do |item, index|
  next unless item.starts_with?('active')

  number_with_active = item.split('active=')[1].to_i
  list[index] = "active=#{(number_with_active+1)%2}"
end

【讨论】:

    猜你喜欢
    • 2015-11-14
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多