10

In the interest of writing cleaner code...

IO.popen("Generate a list of files").readlines.each{ |line|
   chomped_line = line.chomp
   # ...
}
Anthony Mastrean
  • 21,850
  • 21
  • 110
  • 188
HandyGandy
  • 660
  • 2
  • 6
  • 15

4 Answers4

25
IO.popen("Generate a list of files").readlines.map(&:chomp)
buru
  • 3,190
  • 25
  • 35
4
# Example 1
File.readlines("file.txt").each{|line| line.chomp!}

# Example 2
File.readlines("file.txt").map(&:chomp)

# Example 3
File.open("file.txt", "r"){|file| file.readlines.collect{|line| line.chomp}}
Alexandre
  • 141
  • 1
  • 1
  • 5
3
IO.read("something").split($/)

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

steenslag
  • 79,051
  • 16
  • 138
  • 171
  • 1
    Just a note that `$/` matches `\n` newlines strictly while chomp handles `\r\n` as well. If you know that you will only ever have `\n` newlines this solution is _much_ faster than the map/chomp option. – Matt Sanders Aug 16 '16 at 23:35
1

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|
    line.chomp!
    do_something_with line
}
bertramscharpf
  • 175
  • 1
  • 10