Edit each line in a file in Ruby

后端 未结 5 962
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 02:52

I\'m trying to find a simple way of editing each line in a file, and I\'m having some trouble understanding how to use the File class to do so.

The file

5条回答
  •  囚心锁ツ
    2020-12-14 03:29

    I think you misunderstand what this line

    file.each_line { |line| line = line.split(",")[0].to_s }
    

    really does. It takes a line, splits it on a comma, takes the first value, turns it to a string (which it was already), assigns the result to the block-local variable 'line'. And then?
    It goes on to the next line, and nothing is done with the previous one - it's all gone. See the other answers how to remedy this.

提交回复
热议问题