用不同的字符串替换Ruby逗号

时间:2014-06-22 23:52:59

标签: ruby string replace

我有一个名为"示例"的字符串,如下所示:

192.168.1.40,8.8.8.8,12.34.45.56,408, - ,1812
192.168.1.128,192.168.101.222,12.34.45.56,384, - ,1807

我希望获得此输出:

{"字符串1":" 192.168.1.40""字符串2":" 8.8.8.8"“STRING3&#34 ;:“12.34.45.56”,“串,4”:408,“STRING5”:“ - ”," string6":1812} {"字符串1":" 192.168.1.128""字符串2":" 192.168.101.222"“STRING3&#34 ;:“ 12.34.45.56” ,‘串,4’:384,‘STRING5’:‘ - ’," string6":1807}

我这样做了:

example = example.gsub("\n","}\n{\"string1\": \"")                         
example = example.insert(0, "{\"string1\": \"")                  
example = example.concat("}")                                    

我获得了:

{"字符串1":" 192.168.1.40,8.8.8.8,12.34.45.56,408, - ,1812} {"字符串1":" 192.168.1.128,192.168.101.222,12.34.45.56,384, - ,1807}

但我不知道如何进行其他更改。谢谢!

3 个答案:

答案 0 :(得分:3)

好吧,把它作为一个红宝石哈希,你可以输出为json或你需要的任何东西:

out = {}
your_input_data.split(",").each_with_index { |val, i| out["string#{i}"] = val  }

(但你需要为每一行执行此操作:input.lines.each {| line | ...在上面执行上述操作} - 但我不清楚 - 你想要一个地图列表吗?)

答案 1 :(得分:1)

我假设您不希望只是数字的值被双引号。

DATA.each_line do |line|
    l = line.chomp.split(',').map.with_index do |v, i|
        v = v =~ /^\d+$/ ? v : "\"#{v}\""
        "\"string#{i+1}\":#{v}"
    end
    print "{", l.join(','), "}\n"
end

__END__
192.168.1.40,8.8.8.8,12.34.45.56,408,-,1812
192.168.1.128,192.168.101.222,12.34.45.56,384,-,1807

结果:

{"string1":"192.168.1.40","string2":"8.8.8.8","string3":"12.34.45.56","string4":408,"string5":"-","string6":1812}
{"string1":"192.168.1.128","string2":"192.168.101.222","string3":"12.34.45.56","string4":384,"string5":"-","string6":1807}

答案 2 :(得分:0)

从您编写的代码中可以看出,您正在寻找单个字符串作为输出,而不是更精细的Ruby数据结构或输出到打印流。

这对我有用:

example = '192.168.1.40,8.8.8.8,12.34.45.56,408,-,1812
192.168.1.128,192.168.101.222,12.34.45.56,384,-,1807'

result = example.split("\n").map do |line| 
  n = 0 
  line.split(',').map{|s| %Q|"string#{n+=1}":"#{s}"|}.join(',')
end.map{|c| "{#{c}}"}.join("\n")

puts result

{"string1":"192.168.1.40","string2":"8.8.8.8","string3":"12.34.45.56","string4":"408","string5":"-","string6":"1812"}
{"string1":" 192.168.1.128","string2":"192.168.101.222","string3":"12.34.45.56","string4":"384","string5":"-","string6":"1807"}

这会分成行,然后将每一行拆分成单独的字符串,然后将每个字符串与其JSON键连接起来,最后用逗号重新组装join,然后用换行符重新组合。如果你没有列表而不是重新组合的字符串,只需省略相应的连接。