【发布时间】:2011-08-02 13:55:10
【问题描述】:
我目前正在学习 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?
-
我用的是 1.8.7。我应该更新吗?
-
不抱歉..正在考虑其他事情。