开发者

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

开发者 https://www.devze.com 2023-01-16 16:32 出处:网络
In the interest of开发者_StackOverflow中文版 writing cleaner code... IO.popen(\"Generate a list of files\").readlines.each{ |line|

In the interest of开发者_StackOverflow中文版 writing cleaner code...

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


IO.popen("Generate a list of files").readlines.map(&:chomp)


# 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}}


IO.read("something").split($/)

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


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消