【问题标题】:Explanation of 'gets' method: String being printed without any user input?“gets”方法的解释:在没有任何用户输入的情况下打印字符串?
【发布时间】:2017-04-22 21:16:03
【问题描述】:

我正在完成 Learn Ruby the Hard Way 练习,并且对练习 20 中的语法有疑问

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)

在“print_a_line”函数中,如果是字符串插值,则参数“f”,并且在此参数上调用gets.chomp 方法。这是代码运行时出现在控制台上的内容(使用示例文本文件作为 ARGV.first,三行)

First let's print the whole file:
This is Line 1
This is Line 2
This is Line 3
Now let's rewind, kind of like a tape.
Let's print three lines:
1, This is Line 1
2, This is Line 2
3, This is Line 3

我的问题是:为什么我们在“f”参数上调用gets.chomp? “获取”用户输入来自哪里?为什么这行得通,但是仅使用“f”而不使用任何附加方法不会打印文本文件中的行?谢谢!

【问题讨论】:

    标签: ruby methods file-io user-input


    【解决方案1】:

    gets 实际上与用户输入无关。无论是在这种情况下,还是在您可能习惯的“通常”形式中:

    puts "what's your answer?"
    answer = gets.chomp
    

    一般来说,它是一种读取字符串的 IO 对象方法(“字符串”被定义为“从当前位置到(包括)换行符的所有字符”)。

    在您的示例中,它在 File 对象上被调用(因此,从打开的文件中逐行读取内容)。 "naked" form 从文件中读取行,通过命令行参数传递或(如果没有传递文件)从standard input 传递。请注意,标准输入不一定是从键盘读取的(这就是您所说的“用户输入”)。输入数据可以piped到你的程序中。

    但仅使用“f”而不使用任何附加方法不会打印文本文件中的行

    f 是对文件对象的引用。它不代表任何有用的可打​​印内容。但是您可以使用它从文件中读取一些内容,您可以这样做 (f.gets)。

    【讨论】:

    • 好的,删除了错误的链接。很好的答案,也解决了我的困惑。
    • @SergioTulentsev 刚刚完成 - 仍然习惯这些 stackoverflow 程序...再次感谢!
    【解决方案2】:

    文件中的每一行都以换行符 ("\n") 结束,puts 方法显示字符串和换行符,因此它会显示字符串和两个换行符。 chomp 方法将删除字符串末尾的换行符,因此只显示一个换行符。

    查看文档 => https://ruby-doc.org/core-2.2.0/String.html#method-i-chomp

    【讨论】:

      【解决方案3】:

      您看到的gets 不是供用户输入的。相反,它属于 IO 类并读取 IO 流的下一行。 您可以在 Ruby 文档中找到它 https://ruby-doc.org/core-2.3.0/IO.html#method-i-gets

      【讨论】:

      • 谢谢!感谢您的反馈
      猜你喜欢
      • 2020-09-13
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多