Take the 2-minute tour ×

In the interest of writing cleaner code...

IO.popen("Generate a list of files").readlines.each{ |line|
   chomped_line = line.chomp
   # ...
share|improve this question

4 Answers 4

up vote 15 down vote accepted
IO.popen("Generate a list of files").readlines.map(&:chomp)
share|improve this answer

$/ is the separator string. IO.read closes the file after reading.

share|improve this answer
# Example 1
File.readlines("file.txt").each{|line| line.chomp!}

# Example 2

# Example 3
File.open("file.txt", "r"){|file| file.readlines.collect{|line| line.chomp}}
share|improve this answer

I would make it faster and consuming less memory:

  1. use "each_line" rather than "readlines.each". Why read the whole output at once?
  2. use "chomp!" (exclamation mark) to change the string in-place.

Then it is:

IO.popen( "generate_lines").each_line { |line|
    do_something_with line
share|improve this answer

Your Answer


