2

我有一个具有这种结构的文本文件:

regular: 12/09/2010, 15/09/2012, 16/09/2012
rewards: 17/09/2010, 18/09/2012, 19/09/2012
rewards: 20/09/2010, 21/09/2012, 22/09/2012

我想将它存储在这样的矩阵中:

my_matrix = [['regular', '12/09/2010', '15/09/2012', '16/09/2012'],
             ['rewards', '17/09/2010', '18/09/2012', '19/09/2012'],
             ['regular', '20/09/2010', '21/09/2012', '22/09/2012']
            ] 

我试过这个:

File.open(text_file).each_line do |line|

    @costumer_request = line.delete!(':').split
    @costumer_request = line.delete!(',').split

但它返回这个: @costumer_request ['regular', '20/09/2010', '21/09/2012', '22/09/2012']

我该如何解决这个问题?

4

3 回答 3

2
File.open(text_file){|io| io.each_line.map{|line| line.split(/[:,\s]+/)}}
于 2013-04-30T13:03:39.510 回答
2
File.open('foo', 'r') do |f|
  f.lines.map do |line|
    line.chomp.split /[:,] /
  end
end

#=> [
# ["regular", "12/09/2010", "15/09/2012", "16/09/2012"],
# ["rewards", "17/09/2010", "18/09/2012", "19/09/2012"],
# ["rewards", "20/09/2010", "21/09/2012", "22/09/2012"]
#]
于 2013-04-30T13:05:20.850 回答
1

如果您的格式正是您展示的格式,您还可以执行以下操作:

File.open(file).each_line.map do |l|
    l.split.map { |e| e.chomp(/,:/) }
end
于 2013-04-30T13:11:38.690 回答