I have literally just started using Ruby, and I'm looking for a possible alternative to using "gets" for file input... I'm trying to write a simple warmup program that will print out the longest line of a file, like so:
def findMax
maxlength = 0
while line = gets
if line.length > maxlength then
maxlength = line.length
end
end
return maxlength
end
def printLines num
while line = gets
if line.length == num
puts line
end
end
end
printLines findMax
Pretty simple. Find the maximum length, and the use that to print out the longest line, nothing fancy yet. However, whenever I run it with ruby longest.rb < (file) , I get nothing. Is this because I can't use gets in the second while loop because it has nothing more to read? What can I do as an alternative? :)
假设您的文件名为foo.txt
使用File#readlines
将File#readlines
所有行读取到数组中,然后使用Enumerable#sort_by
按行的size
(或length
)对行进行排序,并使用Array#last
来选择排序后的最后一项排列
File.readlines("foo.txt").sort_by { |line| line.size }.last
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.