1

私は Ruby の新しいプログラマーです。ファイルから 2 つの列を取得して、いくつかの操作を実行しようとしています。その目的で正規表現を使用できると思いますか? これは私のファイルです:

 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

一般に、次のように固定幅データを「アンパック」します。

'   1  88    59 '.unpack('A6A6A6')
于 2012-09-06T04:36:07.707 に答える
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

最初の回答に対するあなたのコメントを読んで、これがあなたがやりたいことだと思います:

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 に答える