Volodymyr Hnatiuk Volodymyr Hnatiuk - 8 months ago 49
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

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 Source

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