【问题标题】:Printing out one line of a file in a Ruby script在 Ruby 脚本中打印出文件的一行
【发布时间】:2016-04-24 21:01:07
【问题描述】:

我正在学习“Learn Ruby the Hard Way”,在练习 20 中遇到了 print_a_line 方法。

input_file = ARGV.first
current_file = open(input_file)

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

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)

此方法将获取当前行数,并将该行中的文件内容仅输出到终端。我不明白该方法如何知道打印与current_line 关联的文件行。当我看到这个时,我会认为#{f.gets.chomp) 会返回他们文件的全部内容。该方法如何知道查看current_line 并打印出文件的关联行?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    print_a_line 中调用的 gets 方法从文件中读取一行(不是全部内容)。 current_file 引用的 File 对象跟踪文件中的当前位置,因此每次调用 gets 时,都会返回下一行。

    没有任何东西在查看current_line 以确定要读取哪一行。

    【讨论】:

    • 感谢您的解释!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多