更新的答案,以顯示遍歷所有文件。
我把結果放到一個散列中,這樣可以使用鍵值對來處理數據。新的密鑰可以添加爲計量單位等
runData_20130620.txt
- 活動時間09.87,距離 - 總100.0米
- 活動時間15:19,距離 - 總4.98公里
- 主動持續時間03:00,距離 - 總1.0英里
- 活動時間21:14,距離 - 總3.68,-Sweat生產5.99Gallons
- 活動時間22:31,距離 - 總3.65mi
代碼個
File.foreach("runData_20130620.txt") do |line|
# Create hash, parsing string with regex pattern
runData = Hash[*line.scan(/([^, \-]\D*) (\d*[.:]\d*)/).to_a.flatten]
# This will convert the string keys to symbols, replacing white-space with
# underscores and downcasing
runData = Hash[runData.map { |k,v|
[k.gsub(/\s+/, "_").downcase.to_sym, v] }]
# display results
#runData.each { |k,v| puts "#{k} ** #{v}" }
# display using hash symbol access...
puts "\nRan a distance of #{ runData[:total_distance]} in
runData[:active_duration]} "
puts "Man, I am unfit!" if runData[:sweat_produced]
end
結果
然的100.0的距離在09.87
在15點19
然的4.98的距離在03:00然1.0的距離
然的3.68的距離在21:14
男人,我不適合!
冉3.65 22:31
的距離,你可以發佈一個例子字符串? –