在Ruby中将数组打印为表

时间:2014-05-01 01:57:56

标签: ruby

我目前的代码是......

print_line
processes = @client.sys.process.get_processes
blacklist = ["NT AUTHORITY\\SYSTEM", "NT AUTHORITY\\LOCAL SERVICE", "NT AUTHORITY\\NETWORK SERVICE"]
filtered = processes.map!{|i| i.slice!("arch", "session", "path")}.reject {|h| blacklist.include? h['user']}
filtered.each do |r|
puts r.map { |p| p}.join(" ")
end

这是输出......

pid 0 ppid 0 name [System Process] user 
pid 456 ppid 320 name explorer.exe user CLINE\Administrator
pid 544 ppid 204 name TPAutoConnect.exe user CLINE\Administrator
pid 1096 ppid 456 name vmtoolsd.exe user CLINE\Administrator
pid 180 ppid 456 name rundll32.exe user CLINE\Administrator
pid 1208 ppid 724 name logon.scr user CLINE\Administrator

这是阵列......

[*] [{"pid"=>0, "ppid"=>0, "name"=>"[System Process]", "user"=>""}, {"pid"=>456,       "ppid"=>320, "name"=>"explorer.exe", "user"=>"CLINE\\Administrator"}, {"pid"=>544, "ppid"=>204, "name"=>"TPAutoConnect.exe", "user"=>"CLINE\\Administrator"}, {"pid"=>1096, "ppid"=>456, "name"=>"vmtoolsd.exe", "user"=>"CLINE\\Administrator"}, {"pid"=>180, "ppid"=>456, "name"=>"rundll32.exe", "user"=>"CLINE\\Administrator"}, {"pid"=>1208, "ppid"=>724, "name"=>"logon.scr", "user"=>"CLINE\\Administrator"}]

但我希望输出像一个表,就像这样

pid         ppid        name    user

1           0         x.exe     me

2           1         y.exe    you 

我的代码中缺少什么?

1 个答案:

答案 0 :(得分:1)

您可以使用sprintf打印固定宽度的列。首先得到每列的最大长度,然后使用sprintf并加入"\t"所有值:

max_length = filtered.inject({}) {|m,e| e.each{|key,value| m[key] = [key.length, m[key].to_i, value.to_s.length].max}; m}
puts filtered.collect{|e| e.collect{|key,value| sprintf("%#{max_length[key]}s", value)}.join("\t")}

更新:要打印标题,可以使用以下内容

左对齐:

max_length.collect{|key, value| sprintf("%-#{value}s", key)}.join("\t")

右对齐:

max_length.collect{|key, value| sprintf("%#{value}s", key)}.join("\t")