Volodymyr Hnatiuk Volodymyr Hnatiuk - 11 days ago 5
Ruby Question

Remove " " from line Ruby

I have a loop which read lines from text file :

text = File.open("file.txt").read
text.gsub!(/\n\r?/, "\n", )
text.each_line do |line|
# do something with line
end


And in each iteration I get line with " " in the end of line : "word ", and I need get just "word"

How fix my problem?

ll = line.clone.sub!(" ", "")
- returns nil

Answer

You might want to use String#strip or one of the similar methods to remove whitespace. In this example String#rstrip seems to be an option:

text.each_line do |line|
  sanitized_line = line.rstrip
  # ...
end
Comments