2

Can anyone help me, how to remove the trailing white spaces from each line in a string in ruby.... For example:

str = "Hello everyone. \nHope you guys are doing good  \nstrange i can't remove this spaces"

I tried rstrip but its not working for me.... May be have to try gsub.... I want the answer to be in below wayy.

"Hello everyone.\nHope you guys are doing good\nstrange i can't remove this spaces"
1
  • rstrip strips spaces at the end of a string, not at the end of each line. You could probably use regular expressions to substitute before each \n. Commented Jul 10, 2015 at 16:37

4 Answers 4

4
str.split("\n").map(&:rstrip).join("\n")

Its probably doable with regex but I prefer this way.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use gsub!, which will modify the receiver:

str = "Hello everyone. \nHope you guys are doing good  \nstrange i can't remove this spaces"
str.gsub!(/\s\n/, "\n").inspect
#=> "Hello everyone.\nHope you guys are doing good \nstrange i can't remove this spaces"

Comments

1

Another one using gsub:

str.gsub(/\s+$/, '')
#=> "Hello everyone.\nHope you guys are doing good\nstrange i can't remove this spaces"

/\s+$/ matches one or more spaces (\s+) right before a line break ($)

Comments

0

Or like this

str.each_line.map(&:strip).join("\n")
#=> "Hello everyone.\nHope you guys are doing good\nstrange i can't remove this spaces"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.