简体   繁体   中英

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). 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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