2014-05-01 36 views
0
打印數組作爲表

我當前的代碼是...在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

您可以使用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") 
+0

密鑰可以添加到每列的頂部嗎? – user3219834

+0

當然,看更新.. – Candide