2016-08-25 113 views
-1

我在這樣的陣列 -顯示陣列中的表格形式

arr = ["0.5", " 2016-08-25 11:02:00 +0530", " test 1", 
     " 0.75", " 2016-08-25 11:02:00 +0530", " test 2"] 

,我希望它被顯示以表格形式這樣的 -

0.5 11:02 test 1 
0.75 11:02 test 2 

回答

5
a = ["0.5", " 2016-08-25 11:02:00 +0530", " test 1", " 0.75", " 2016-08-25 11:02:00 +0530", " test 2"] 

a.each_slice(3) do |x, y, z| 
    puts "#{x.strip} #{y[/\d\d:\d\d/]} #{z.strip}" 
end 
1

另一種方法:

arr = ["0.5", " 2016-08-25 11:02:00 +0530", " test 1", " 0.75", " 2016-08-25 11:02:00 +0530", " test 2"] 

arr.each_slice(3).map do |x| 
    x[1] = Time.parse(x[1]).strftime("%H:%M"); x.map(&:strip) 
end.map{ |y| puts y.join(' ') } 

0.5 11:02試驗1
0.75 11:02試驗2

1

我加入的arr元素成一個字符串與每個元素之間的空間,然後掃描的字符串,保存結果到三個捕獲基團,它產生了一個包含兩個三元素數組的數組。最後,我加入了兩個陣列中每一個的三個元素,並使用puts打印結果。是

r =/
    (\d+\.\d+) # match a float in capture group 1 
    .+?   # match > 1 of any characters, lazily (?) 
    (\d{1,2}:\d2) # match the time in capture group 2 
    .+?   # match > 1 of any characters, lazily (?) 
    (test\s\d+) # match 'test' followed by > 1 digits in capture group 3 
    /x   # free-spacing regex definition mode 

puts arr.join(' ').scan(r).map { |a| a.join(" ") } 

打印

0.5 11:02 test 1 
0.75 11:02 test 2 

三個步驟如下。

a = arr.join(' ') 
    #=> "0.5 2016-08-25 11:02:00 +0530 test 1 0.75 2016-08-25 11:02:00 +0530 test 2" 
b = a.scan(r) 
    #=> [["0.5", "11:02", "test 1"], 
    # ["0.75", "11:02", "test 2"]] 
c = b.map { |a| a.join(" ") } 
    #=> ["0.5 11:02 test 1", "0.75 11:02 test 2"] 

然後puts c打印上面顯示的結果。