1

我是 Ruby 的新程序员。我正在尝试从文件中获取两列并执行一些操作。我想我可以为此目的使用正则表达式?这是我的文件:

 MMU June 2002

  Dy MxT   MnT   AvT   HDDay  AvDP 1HrP TPcpn WxType PDir AvSp Dir MxS SkyC MxR MnR AvSLP

   1  88    59    74          53.8       0.00 F       280  9.6 270  17  1.6  93 23 1004.5
   2  79    63    71          46.5       0.00         330  8.7 340  23  3.3  70 28 1004.5
   3  77    55    66          39.6       0.00         350  5.0 350   9  2.8  59 24 1016.8
   4  77    59    68          51.1       0.00         110  9.1 130  12  8.6  62 40 1021.1
   5  90    66    78          68.3       0.00 TFH     220  8.3 260  12  6.9  84 55 1014.4
   6  81    61    71          63.7       0.00 RFH     030  6.2 030  13  9.7  93 60 1012.7
   7  73    57    65          53.0       0.00 RF      050  9.5 050  17  5.3  90 48 1021.8
   8  75    54    65          50.0       0.00 FH      160  4.2 150  10  2.6  93 41 1026.3
   9  86    32*   59       6  61.5       0.00         240  7.6 220  12  6.0  78 46 1018.6

这就是我想要做的:

 result_arr = []
 File.open("filename") do |f|
    while (line = f.gets)
      ary = line.split
      day = ary[0]
      max = ary[1]
      min = ary[2]
      result = max.to_i - min.to_i
     result_arr << result unless result == 0
   end
   puts result_arr.min
 end
 ~    

基本上我想打印第一列和 min(Mxt - Mnt) 的结果我正在使用一个数组,但我正在尝试使用 2D 可能不知道该怎么做

非常感谢。

4

3 回答 3

0

阅读您对第一个答案的评论,我认为这就是您想要做的:

results = [] #array to store the difference between the "Mxt" and "Mnt" fields

File.open("/path/to/file").each do |line|
  # skip header rows (there seem to be multiple in the file)
  # you might need to adjust the regex that checks for the presence of a data row
  # here I'm assuming that data rows start with a digit
  if line =~ /^\d/
    arr = line.split
    # you can use the column indices to get to the data you want
    results << arr[1] - arr[2]  
  end
end
于 2012-09-06T03:07:39.647 回答
0

以下情况如何:

File.open("file.txt") do |f|
  while (line = f.gets)
    ary = line.split
    do_whatever_you_want_to(ary)
  end
end

String#split 会将你的行变成一个数组,在空格和制表符处中断。

于 2012-09-06T01:25:16.707 回答
0

通常,您希望像这样“解压”固定宽度的数据:

'   1  88    59 '.unpack('A6A6A6')
于 2012-09-06T04:36:07.707 回答