【问题标题】:LRTHW exercise 20 strange outputLRTHW练习20怪输出
【发布时间】: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


【解决方案1】:

我删除了 test.txt 文件并从头开始重新创建它,这使得代码可以完美运行。我不是 100% 知道为什么,但我有一种预感,因为在许多不同的测试中重用该文件并在 Powershell 中玩耍,我无意中在文件中留下了一些奇怪的格式,导致它的行为有所不同。

【讨论】:

  • 其中可能有一些疯狂的东西,当输出时,会导致终端自行绘制。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多