Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 文件中的文本打印不正确_Ruby_Learn Ruby The Hard Way - Fatal编程技术网

Ruby 文件中的文本打印不正确

Ruby 文件中的文本打印不正确,ruby,learn-ruby-the-hard-way,Ruby,Learn Ruby The Hard Way,通过解决这个问题,我输入了与问题状态完全相同的代码——甚至尝试复制和粘贴,以查看是否是我做错了什么,但不是 我的代码在这篇文章的底部。我正在发送参数“test.txt”,其中包含: This is stuff I typed into a file. It is really cool stuff. Lots and lots of fun to have in here 但是,当我运行代码时,在print_all(当前_文件)期间,它只打印“这里有很多很多乐趣”-这是文件的最后一行 在打

通过解决这个问题,我输入了与问题状态完全相同的代码——甚至尝试复制和粘贴,以查看是否是我做错了什么,但不是

我的代码在这篇文章的底部。我正在发送参数“test.txt”,其中包含:

This is stuff I typed into a file. 
It is really cool stuff. 
Lots and lots of fun to have in here
但是,当我运行代码时,在print_all(当前_文件)期间,它只打印“这里有很多很多乐趣”-这是文件的最后一行

在打印每一行的地方,它打印:

1 ["This is stuff I typed into a file. \rIt is really cool stuff. \rLots and lots of fun to have in here.\r\r"]
2 []
3 []'
基本上,将所有行捕获为一行,在应该打印第2行和第3行的地方不打印任何内容

有什么想法吗

input_file = ARGV[0]

def print_all(f)
  puts f.read()
end

def rewind(f)
  f.seek(0, IO::SEEK_SET)
end

def print_a_line(line_count, f)
  puts "#{line_count} #{f.readlines()}"
end

current_file = File.open(input_file)

puts "First let's print the whole file:"
puts # a blank line

print_all(current_file)

puts "Now let's rewind, kind of like a tape."

rewind(current_file)

puts "Let's print three lines:"

current_line = 1
print_a_line(current_line, current_file)

current_line += 1
print_a_line(current_line, current_file)

current_line += 1
print_a_line(current_line, current_file)
编辑: 您正在使用的测试文件似乎只包含字符
\r
以指示换行符,而不是windows
\r\n
或linux
\n
。您的文本编辑器可能会将
\r
解释为换行符,但ruby不会

原始答复:

至于你的第一个问题,我无法重现。如何运行脚本

在第二个问题中,您使用的是
file.readline()
(注意最后的s)方法,而不是
file.readline()

读取整个文件并以数组形式返回其内容,每行作为数组的一个元素。 这就是为什么你第一次打电话就得到了你的全部文件。后续调用返回空数组,因为您是文件的结尾(您需要像以前一样“倒带”以继续读取文件)

读取文件的一行并以字符串形式返回其内容,这可能是您想要的


我链接到ruby文档以进一步阅读(没有双关语)。请注意,
IO
类的文档中详细介绍了相关方法,因为
File
继承自该类,而readline/readline方法继承自
IO

,感谢您的响应。关于你的第一个问题,我在terminal:ruby Lesson20.rb test.txt中运行脚本关于你的第二个语句-我实际上使用了readlineS,这是我运行代码的唯一方法。使用readline,我得到以下错误lesson20.rb:12:in
readline]:lesson20.rb:12:in
print_______________________________________<代码>EOFError通常在一个文件上调用readline而没有更多行可读取时引发。这意味着你的文件中看起来有三行的内容实际上被视为一行。这已经解决了-杜瑞尔说他无法重现我的第一个问题我想这可能是我实际用作论点的文件的问题。因此,我创建了一个新文件,并通过传递该文件来测试代码,结果成功了。我试图使用的文件一定有问题-我在之前的练习中学习文件访问时使用过它,所以可能是指针弄错了。