【问题标题】:Passing an gets.chomp as an argument传递 gets.chomp 作为参数
【发布时间】:2017-05-02 06:34:57
【问题描述】:
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 "Let's rewind kind a 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)

我确信有一个与此类似的帖子,但我的问题有点不同。如上所示,print_a_line 方法有两个参数 line_count 和 f。

1) 据我了解, line_count 参数仅用作 current_line 变量,它只是一个整数。它与 rewind(f) 方法有什么关系,因为当我运行代码时,方法 print_a_line 显示如下:

1, Hi
2, I'm a noob

其中 1 是第一行,2 是第二行。 line_count 只是一个数字,ruby 怎么知道 1 是第 1 行,2 是第 2 行?

2) 为什么在方法 print_a_line 中使用gets.chomp?如果我像这样通过 f

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

我会得到一个疯狂的结果

1, #<File:0x007fccef84c4c0>
2, #<File:0x007fccef84c4c0>

【问题讨论】:

    标签: ruby arguments seek


    【解决方案1】:

    因为IO#gets 从可读 I/O 流(在本例中为文件)读取下一行,并在读取成功且未到达文件末尾时返回 String 对象。而且,chomp 会从 String 对象中删除回车符。

    所以当你有一个包含如下内容的文件时:

    This is file content.
    This file has multiple lines.
    

    代码将打印出来:

    1, This is file content.
    2, This file has multiple lines.
    

    在第二种情况下,您传递的是文件对象本身而不是读取它。因此,您会在输出中看到这些对象。

    【讨论】:

      猜你喜欢
      • 2015-06-02
      • 2016-01-01
      • 2016-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多