新手问题 Ruby 应该怎样处理「Key: Value」文本

gotnix · 2015年01月22日 · 最后由 gotnix 回复于 2015年01月30日 · 2570 次阅读

Ruby 是 CentOS 的 RPM 安装的,版本是 1.8.7。 要处理的文本如下(「description: 」这行没有值,下面那行是空行):

irb(main):001:0> require 'rubygems'
=> true
irb(main):002:0> require 'socket'
=> true
irb(main):003:0> SOCKET = '/var/run/haproxy/haproxy.sock'
=> "/var/run/haproxy/haproxy.sock"
irb(main):004:0> UNIXSocket.open(SOCKET) do |socket|
irb(main):005:1*   socket.write("show info")
irb(main):006:1>   socket.each do |line|
irb(main):007:2*     puts line.chomp
irb(main):008:2>   end
irb(main):009:1> end
Name: HAProxy
Version: 1.4.22
Release_date: 2012/08/09
Nbproc: 1
Process_num: 1
Pid: 32163
Uptime: 47d 21h34m45s
Uptime_sec: 4138485
Memmax_MB: 0
Ulimit-n: 8231
Maxsock: 8231
Maxconn: 4096
Maxpipes: 0
CurrConns: 1
PipesUsed: 0
PipesFree: 0
Tasks: 27
Run_queue: 1
node: vm-haproxy-233
description: 

=> #<UNIXSocket:0x7f38f50ec380>

我想把 SOCKET 返回的「Key: Value」格式的文本转换成方便 Ruby 处理的数据,现在是转成 Hash 了,如下:

UNIXSocket.open(SOCKET) do |socket|
  h = Hash.new
  socket.write("show info")
  socket.each do |line|
    arry = line.chomp.split(':')
    h["#{arry[0]}".downcase] = "#{arry[1]}".lstrip unless arry.empty?
  end
  h.each {|key, value| puts "#{key}#{value}"}
end

还有就是先生成一个数组,最后一次转成 Hash:

irb(main):073:0> a1 = [["ulimit-n", 8231], ["memmax_mb", 0], ["maxconn", 4096]]
=> [["ulimit-n", 8231], ["memmax_mb", 0], ["maxconn", 4096]]
irb(main):076:0> h2 = Hash[a1.map {|k, v| [k, v]}]
=> {"ulimit-n"=>8231, "memmax_mb"=>0, "maxconn"=>4096}

想请教一下,我这么做是否合适,大家遇到类似的情况是怎么处理的;这里可以用 OpenStruct 来处理么? 请多多指教!

result = YAML::load socket

存入 yml.txt

Name: HAProxy
Version: 1.4.22
Release_date: 2012/08/09
Nbproc: 1
Process_num: 1
Pid: 32163
Uptime: 47d 21h34m45s
Uptime_sec: 4138485
Memmax_MB: 0
Ulimit-n: 8231
Maxsock: 8231
Maxconn: 4096
Maxpipes: 0
CurrConns: 1
PipesUsed: 0
PipesFree: 0
Tasks: 27
Run_queue: 1
node: vm-haproxy-233
description: 

YAML.load(File.new('yml.txt')) 结果为

{"Name"=>"HAProxy",
 "Version"=>"1.4.22",
 "Release_date"=>"2012/08/09",
 "Nbproc"=>1,
 "Process_num"=>1,
 "Pid"=>32163,
 "Uptime"=>"47d 21h34m45s",
 "Uptime_sec"=>4138485,
 "Memmax_MB"=>0,
 "Ulimit-n"=>8231,
 "Maxsock"=>8231,
 "Maxconn"=>4096,
 "Maxpipes"=>0,
 "CurrConns"=>1,
 "PipesUsed"=>0,
 "PipesFree"=>0,
 "Tasks"=>27,
 "Run_queue"=>1,
 "node"=>"vm-haproxy-233",
 "description"=>nil}

多谢回复,用了一楼的方法。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号