【问题标题】:How can I chomp every line in an array at once?我怎样才能一次咀嚼数组中的每一行?
【发布时间】:2010-09-20 10:43:50
【问题描述】:

为了编写更简洁的代码...

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

【问题讨论】:

    标签: ruby arrays chomp


    【解决方案1】:
    IO.popen("Generate a list of files").readlines.map(&:chomp)
    

    【讨论】:

      【解决方案2】:
      # 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}}
      

      【讨论】:

        【解决方案3】:
        IO.read("something").split($/)
        

        $/ 是分隔符字符串。 IO.read 读取后关闭文件。

        【讨论】:

        • 请注意,$/ 严格匹配 \n 换行符,而 chomp 也处理 \r\n。如果你知道你只会有 \n 换行符,这个解决方案比 map/chomp 选项快很多
        【解决方案4】:

        我会让它更快,消耗更少的内存:

        1. 使用“each_line”而不是“readlines.each”。为什么要一次读取整个输出?
        2. 使用“咬!” (感叹号)就地更改字符串。

        那就是:

        IO.popen( "generate_lines").each_line { |line|
            line.chomp!
            do_something_with line
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-16
          • 2017-12-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-08-20
          • 2018-07-01
          • 2022-12-20
          相关资源
          最近更新 更多