如何重构这个简单的 Ruby 算法
好的,我有这个 ruby 脚本,它打开一个文件并将每一行传递给 line_parser 方法。此方法只是将制表符更改为几个空格。如下所示:
$lines = []
def line_parser(line)
line.gsub! /\t/, ' '
$lines[$lines.length] = line
end
f = File.open(ARGV[0], 'r').each { |line| line_parser(line) }
f.close
f = File.open(ARGV[0], 'w')
$lines.each { |line| f.puts line}
f.close
如您所见,它有两个循环; 一个循环迭代文件内的文本行并将它们放入数组内。另一个循环使用最近创建的数组中的新行重新写入文件。
我认为我的问题很简单: 如何重构此代码片段,以便仅在一个循环内执行上述所有步骤?
我知道这是可以完成的,只是用我目前的 Ruby 知识还无法做到这一点。
提前致谢!
Ok, I have this ruby script which opens a file and passes each line to the line_parser method. This method simply changes tabs for a couple of spaces. Here it is:
$lines = []
def line_parser(line)
line.gsub! /\t/, ' '
$lines[$lines.length] = line
end
f = File.open(ARGV[0], 'r').each { |line| line_parser(line) }
f.close
f = File.open(ARGV[0], 'w')
$lines.each { |line| f.puts line}
f.close
As you can see it has two loops; one loop to iterate over the lines of text inside the file an place them inside of an array. And the other loop writes the file all over again with the new lines from the recently created array.
My question is simple I think:
How can I refactor this snippet so that I do all the steps described above inside one loop only?
I know it can be done, I just have not been able to do it with my current ruby knowledge.
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这只是迭代文件一次,但在最终将其写入文件之前仍然必须将文件缓存在字符串中。如果您想避免缓存,则必须先写入临时文件。完成读/写后,您只需删除旧文件并通过重命名将其替换为新的临时文件。
This just iterates over the file once but it still has to cache the file in a string before finally writing it to the file. If you want to avoid caching you will have to write to a temporary file first. Once done reading/writing you would simply delete the old file and replace it with the new temporary file by renaming it.
请注意,这实际上是被骗的。读取整个文件实际上是一个循环。
但由于您正在读取然后写入同一个文件,我怀疑您是否可以避免
2 个循环(一个用于读取,一个用于写入)。
Please note that this is actually cheated. Reading the whole file is in fact a loop.
But since you are reading and then writing to the same file, I doubt you can avoid having
2 loops (one for reading and one for writing).
我们可以使用 rubygems 吗?
Can we use rubygems?