【发布时间】:2014-11-06 16:43:35
【问题描述】:
对于这个练习,我完美地编写了所有代码,甚至通过逐字复制和粘贴书中的代码(Learn Ruby the Hard Way)进行了仔细检查。出于某种原因,当我调用print_a_line() 函数时,它不会打印出我通过的current_line 参数,直到第三次调用它会在行前打印出3。是否有一些我在这里错过的 IO 流的刷新或 Powershell 的一些细微差别?
我在 Windows 8 64 位机器上运行 Ruby 2.0.0p576 (x64)。
代码:
input_file = ARGV.first
def print_all(f)
puts f.read
end
def rewind(f)
f.seek(0)
end
def print_a_line(line_count, f)
puts "#{line_count}, #{f.gets.chomp}"
end
current_file = open(input_file)
puts "First let's print the whole file:\n"
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 = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
【问题讨论】:
-
你的输出是什么样的?
-
除了打印行号外,它什么都有。例如:
, This is line 1., This is line 2.3, This is line 3. -
这对我有用,所以我不确定你看到了什么或者为什么会出现故障。您是否正在运行此代码?你是用
ruby还是irb运行它? -
我正在运行该代码,并使用外部 .rb 文件中的 ruby 运行它。我可以截屏我的输出吗?
-
纯文本完全不需要截图。这段代码按原样工作得很好,所以我很好奇可能出了什么问题。您还有其他地方或方式可以运行它吗?
标签: ruby powershell output