Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I chomp every line in an array at once?

Tags:

arrays

ruby

chomp

In the interest of writing cleaner code...

IO.popen("Generate a list of files").readlines.each{ |line|
   chomped_line = line.chomp
   # ...
}
like image 444
HandyGandy Avatar asked Sep 20 '10 10:09

HandyGandy


2 Answers

IO.popen("Generate a list of files").readlines.map(&:chomp)
like image 119
buru Avatar answered Oct 22 '22 03:10

buru


# 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}}
like image 32
Alexandre Avatar answered Oct 22 '22 03:10

Alexandre