2010-10-04 69 views
0

我只想獲得c79363上的學生信息。Ruby正則表達式 - 速度問題

以下文件(users.txt)包含用戶ID的

c79363::7117:dputnam,gliao01,hmccon01,crober06,cpurce01,cdavid03,dlevin01,jsmith88 
d79363::7117:dputn,gliao0,hmcc01,crob06,cpur01,cdad03,dlen01,jsmh88 
f79363::7117:dpnam,gli01,hmcn01,ober06,crce01,cdav03,dln01,jith88 

FILENAME=user_info.txt 

另外一個包含有關用戶的特定信息,如以這種格式

jsmith88:*:4185:208:jsmith113:/students/jsmith88:/usr/bin/bash 
userd:*:4185:208:jsmith113:/students/jsmith88:/usr/bin/bash 
gliao01:*:4185:208:jsmith113:/students/jsmith88:/usr/bin/bash 

這裏是我的解決方案,但很慢!我想優化速度。

僞代碼

I read the file using File.readlines(users.txt) -> 
I used split(/,/) -> I then pop array until i had an array with the following values 
dputnam,gliao01,hmccon01,crober06,cpurce01,cdavid03,dlevin01,jsmith88 

I then continue to read user_info.txt with File.readlines(user_info.txt) 
I split(/:/) i have USER ARRAY 

Finally I compared the first entry USER ARRAY with my users in class c79363. 
+0

也許最好只發布真正的代碼。 – rfunduk 2010-10-04 18:51:56

+0

ruby​​-prof gem會告訴你你的瓶頸在哪裏 – rogerdpack 2010-10-04 18:54:52

+0

如果你只有一個數據庫而不是文本文件... – JoshD 2010-10-04 18:55:52

回答

0
user_info = {} 
File.foreach("user_info.txt") {|line| user_info[line[/^[^:]+/]] = line.chomp} 

class_name = "c79363" 
File.foreach("users.txt") do |line| 
    next unless line[/^[^:]+/] == class_name 
    line[/[^:]+$/].rstrip.split(/,/).each do |user| 
     puts user_info[user] if user_info.has_key?(user) 
    end 
end 
0
user_info = {} 
File.readlines("users_info.txt").each do |line| 
    user_info[line.split(/:/,2)[0]] = line.chomp 
end 
class_name = "c79363" 
File.readlines("users.txt").each do |line| 
    line=line.strip.split(/:/) 
    if line[0] == class_name then 
     line[-1].split(",").each {|u| puts user_info[u] if user_info[u] } 
    end 
end