简体   繁体   English

从文件Ruby中打印最长的行

[英]Print longest line out of a file Ruby

I am trying to print the longest line in the file 'words', which is a file with a list of words (each in a new line). 我正在尝试在文件'words'中打印最长的一行,该文件是带有单词列表的文件(每个单词都换行)。 With this code below, I get it to print each line that was longer than the previous compared to. 通过下面的代码,我可以打印出比以前更长的每一行。 However, I need it to just print the longest line out of the whole file. 但是,我需要它仅打印整个文件中最长的一行。

I am still new with Ruby and I can't seem to find the answer on google. 我还是Ruby的新手,我似乎在google上找不到答案。

max = 0
IO.foreach('words') do |line|
    if line.length > max
        max = line.length  
        print line 
    end
end

I would really appreciate your help. 我将衷心感谢您的帮助。

You'll need to keep track of the longest line, and only print when done. 您需要跟踪最长的一行,并且仅在完成后才打印。

Something like this: 像这样:

max = 0
longest = ""
IO.foreach('words') do |line|
    if line.length > max
        max = line.length  
        longest = line 
    end
end
print longest

一种更简洁和Ruby风格的方法是

puts IO.foreach('words').max_by(&:length)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM