【问题标题】:loop, array and file problem in rubyruby 中的循环、数组和文件问题
【发布时间】: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。我应该更新吗?
  • 不抱歉..正在考虑其他事情。

标签: ruby arrays loops file-io


【解决方案1】:

删除文件中的重复行:

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

不用写那么多代码了:)

【讨论】:

  • 哇,好的,确实,非常棒。
【解决方案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"))}

【讨论】:

  • 嗯,很好,但最后我得到了一个空文件:/
  • 你能告诉我们变量'unique_lines'的值是多少吗?
  • 还是返回一个空文件,但是在shell中join有效
  • 我仍然看到你错过了 f.puts 调用中的 join 语句
  • 好吧,什么也没说,它有效,只是它没有“咬”行
【解决方案3】:

关于原始代码的几点说明:

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

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

如果你想构建一个行数组,那么你可以写

fileArray = openFile.readlines

如果您希望这些行是chomped(通常是个好主意),那么可以通过类似的方式来实现

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

甚至(因为文件混入Enumerable

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

还有一件小事:Ruby 测试与 === 的相等性仅用于赋值,所以

if items = items2

items 设置为items2(并将始终评估为true

【讨论】:

    猜你喜欢
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 2013-04-09
    相关资源
    最近更新 更多