如何在矩阵中存储文件的每一行?

时间:2013-04-30 12:58:43

标签: ruby

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

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']

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

File.open(text_file){|io| io.each_line.map{|line| line.split(/[:,\s]+/)}}

答案 1 :(得分: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"]
#]

答案 2 :(得分:1)

如果您的格式正是您所显示的格式,您也可以这样做:

File.open(file).each_line.map do |l|
    l.split.map { |e| e.chomp(/,:/) }
end