user3290526
user3290526

Reputation: 139

Printing lines of a file in ruby

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? :)

Upvotes: 1

Views: 115

Answers (1)

bjhaid
bjhaid

Reputation: 9762

Suppose your file name is foo.txt use File#readlines to read all the lines in the file into an array then Enumerable#sort_by to sort the lines by their size(or length) and Array#last to pick the last item in the sorted array

File.readlines("foo.txt").sort_by { |line| line.size }.last

Upvotes: 1

Related Questions