我正在尝试以ASCII格式将哈希哈希打印到日志文件中的表中。我有一个哈希值,其值也是一个哈希值,它的值是一个列表:
irb(main):057:0> h = {
irb(main):058:1* 'mode1' => {
irb(main):059:2* 'name1' => [2, 4],
irb(main):060:2* 'name2' => [54, 65]
irb(main):061:2> },
irb(main):062:1* 'mode2' => {
irb(main):063:2* 'name4' => [3, 0],
irb(main):064:2* 'name3' => [2, 1]
irb(main):065:2> },
irb(main):066:1* 'mode3' => {
irb(main):067:2* 'xys' => [100, 28]
irb(main):068:2> }
irb(main):069:1> }
我希望将其打印为:
**************************************************************************************
| No | Mode Name | Sub Name | Value 1 | Value 2 |
**************************************************************************************
| 1 | mode1 | name1 | 2 | 4 |
| | | name2 | 54 | 65 |
--------------------------------------------------------------------------------------
| 2 | mode2 | name4 | 3 | 0 |
| | | name3 | 2 | 1 |
--------------------------------------------------------------------------------------
| 3 | mode3 | xys | 100 | 28 |
**************************************************************************************
printf
,但是我无法弄清楚如何使用hash.each
块进行居中对齐,当内部哈希有多个键时我被卡住了。我不需要打印第一列和第二列。我正在使用ruby 1.8.6 (2009-08-04 patchlevel 383)
。
答案 0 :(得分:0)
基于“What is the “right” way to iterate through an array in Ruby?”:
puts "*" * <number of asterisks>
puts "|\tNo\t|\tMode\t|..."
puts "*" * <number of asterisks>
number = 1
for mode in h.keys.sort
first = true
for subkey in mode.keys.sort
if first
puts "|\t#{number.inspect}\t|\t#{h[mode].inspect}\t|\t#{subkey.inspect}\t|..."
first = false
else
puts "|\t\t|\t\t|\t#{subkey.inspect}\t|..."
end
puts "-" * <number of dashes>
end
number += 1
end