加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

gets.chomp在ruby中的函数内部

发布时间:2020-12-17 03:49:27 所属栏目:百科 来源:网络整理
导读:我正在经历“以艰难的方式学习 Ruby”,而在练习20中,有一段我不理解的代码片段.我不明白为什么在函数“print_a_line”中调用f的gets.chomp. input_file = ARGV.firstdef print_all(f) puts f.readenddef rewind(f) f.seek(0)enddef print_a_line(line_count,
我正在经历“以艰难的方式学习 Ruby”,而在练习20中,有一段我不理解的代码片段.我不明白为什么在函数“print_a_line”中调用f的gets.chomp.

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)

因此,我不明白输出的第二部分是如何产生的.我理解它是传递给代码的test.txt文件的前3行,但我不明白f.gets.chomp是如何产生这一行的.

$ruby ex20.rb test.txt
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

解决方法

File对象f跟踪它在文件中读取的位置(以及它引用的内容跟踪).您可以将其视为在文件中读取时前进的光标.当你告诉f获取时,它会一直读到它到达新行.它们的关键是f记住你的位置,因为读数会提升“光标”. chomp call根本不进入这个部分.因此,每次调用f.gets只会读取文件的下一行并将其作为字符串返回.

chomp只是操作f.gets返回的字符串,对File对象没有影响.

编辑:要完成答案:chomp返回删除了尾部换行符的字符串. (从技术上讲,它删除了记录分隔符,但这几乎与新行不同.)这来自Perl(AFAIK),其想法是,基本上你不必担心你的特定输入形式是否通过了你是否换行符.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读