2016-08-25 104 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打印上面显示的结果。