2011-08-02 18 views
1

我目前在学习ruby,这里是我想要做的: 一个脚本,它打开一个文件,进行置换,然后比较每一行,看看它是否存在很多次。 所以,我试图直接使用字符串,但我没有找到如何去做,所以我把每一行放在一个数组中,并比较每一行。 但我得到了第一个问题。 这里是我的代码:ruby​​中的循环,数组和文件问题

#!/usr/bin/env ruby 

DOC = "test.txt" 
FIND = /,,^M/ 
SEP = "\n" 

#make substitution 
puts File.read(DOC).gsub(FIND, SEP) 

#open the file and put every line in an array 
openFile = File.open(DOC, "r+") 
fileArray = openFile.each { |line| line.split(SEP) } 
#print fileArray #--> give the name of the object 
#Cross the array to compare every items to every others 
fileArray.each do |items| 
items.chomp 
     fileArray.each do |items2| 
     items2.chomp 
       #Delete if the item already exist 
       if items = items2 
         fileArray.delete(items2) 
       end 
     end 
end 
#Save the result in a new file 
File.open("test2.txt", "w") do |f| 
     f.puts fileArray 
end 

最后,我只有数组对象“fileArray”的名称。我在分割之后打印对象,并且我得到了相同的结果,所以我猜这个问题是从这里开始的。需要一点帮助(如果你知道如何在没有数组的情况下做到这一点,只需使用文件中的行,也可以欣赏)。 谢谢!

编辑: 所以,这里是我的代码现在

#!/usr/bin/env ruby 

DOC = "test.txt" 
FIND = /,,^M/ 
SEP = "\n" 

#make substitution 
File.read(DOC).gsub(FIND, SEP) 

unique_lines = File.readlines(DOC).uniq 
#Save the result in a new file 
File.open('test2.txt', 'w') { |f| f.puts(unique_lines) } 

无法弄清楚如何终日啃食这一点。

+0

哪个版本的Ruby是你在用吗? 1.8还是1.9? – Casper

+0

我使用1.8.7。我应该更新吗? – Simon

+0

没有抱歉..正在想别的东西。 – Casper

回答

2

修改你的代码是这样的:

f.puts fileArray.join("\n") 

另一种方法:

unique_lines = File.readlines("filename").uniq 
# puts(unique_lines.join("\n")) # Uncomment this line and see if the variable holds the result you want... 
File.open('filename', 'w') {|f| f.puts(unique_lines.join("\n"))} 
+0

嗯,很好,但最后我得到了一个空文件:/ – Simon

+0

您能告诉我们变量'unique_lines'的值是什么? –

+0

我会编辑我的第一条消息;) – Simon

3

删除重复行的文件:

no_duplicate_lines = File.readlines("filename").uniq 

没有必要写那么多代码:)

+0

哇,确实,非常棒。 – Simon

2

Jus T A几个点对原代码:

fileArray = openFile.each { |line| line.split(SEP) } 

fileArrayFile对象,我怀疑是不是你的意图。 File#each#表示法是用于描述所提供类的对象上的特定方法的Ruby约定)为每行执行提供的块(它也可用于同义词:each_line),其中一行默认定义为操作系统的结束行字符。

如果你正在寻找建立线的阵列,那么你可以只写了

fileArray = openFile.readlines 

,如果你想那些线路是chomp ED(通常是一个好主意),那么可以通过以下方式实现像

fileArray = openFile.readlines.collect { |line| line.chomp } 

甚至(因为文件中Enumerable混合)

fileArray = openFile.collect { |line| line.chomp } 

和另外一个小东西:Ruby的测试具有==平等,=仅用于分配,所以

if items = items2 

将设置itemsitems2(而且将永远评估为true

+0

感谢所有这一切:) – Simon