I am just learning RUBY and am very impressed, I one week I've built tree routines that will save my group 6 to 7 hours each week, and they run in 2 minutes. Pretty cool. I would appreciate a suggest on how to do some. I have a script that correctly parses a directory full of text file and extracts key data. The data lines look like this:
" category value"
I have 15 categories and the code below works. But is crude. I create 15 global arrays and match each line "category" to the text trying in the case statement. Would hash or an object work better. Just looking for pointer of which way to direct my research. Thanks!
Below is part of a big loop that goes through each found line for each document, and is in its own method.
#Create a hash, so that when you use a #key that doesn't exist, it creates the key, #assigns it the array [0,0], and returns the #array:
categories = Hash.new() do |hash, key|
hash[key] = [0,0]
end
#Loop over each line in a file:
File.foreach("data.txt") do |line|
arr = line.split(":")
cat = arr[0].strip
val = Float(arr[1]) #causes an error if can't convert
categories[cat][0] += 1
categories[cat][1] += val
end
p categories
puts categories["Make pie"][0]
puts categories["Redo size"][1]
Using this data:
Redo size: 1.1
Logical reads: 2.1
Redo size: 1.1
Hello world: 3.1
Make pie: 4.1
Hello world: 3.1
Make pie: 4.1
Make pie: 4.1
File.foreach "foo.dat" do |line|
if /^\s+\b(.+?)\b\s+(\d+\.\d+)/ =~ line
s = stats[$1]
s.count += 1
s.sum += Float($2)
end
end
Note, you might have to tweak the regexp.
Kind regards
robert
···
2007/10/30, Robert Keller <rlkeller@yahoo.com>:
I am just learning RUBY and am very impressed, I one week I've built tree routines that will save my group 6 to 7 hours each week, and they run in 2 minutes. Pretty cool. I would appreciate a suggest on how to do some. I have a script that correctly parses a directory full of text file and extracts key data. The data lines look like this:
" category value"
I have 15 categories and the code below works. But is crude. I create 15 global arrays and match each line "category" to the text trying in the case statement. Would hash or an object work better. Just looking for pointer of which way to direct my research. Thanks!
--
use.inject do |as, often| as.you_can - without end