我目前在学习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) }
无法弄清楚如何终日啃食这一点。
哪个版本的Ruby是你在用吗? 1.8还是1.9? – Casper
我使用1.8.7。我应该更新吗? – Simon
没有抱歉..正在想别的东西。 – Casper