我有这样一个数组 -
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
答案 0 :(得分: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 :(得分: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
答案 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
打印上面显示的结果。