Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to remove trailing backslashes from a string?

I have a string like

"car\"

which I will be storing in postgres db. I want to remove the backslash from the string before saving. Is there a way I can do that in ruby or in postgres? When I try to remove it in ruby, it considers the quote after the backslash as an escape character.

like image 344
Ari53nN3o Avatar asked Oct 15 '12 14:10

Ari53nN3o


3 Answers

See following code:

1.9.3p125 :022 > s = "cat\\"
 => "cat\\" 
1.9.3p125 :023 > puts s
cat\
 => nil 
1.9.3p125 :024 > s.chomp("\\")
 => "cat" 
1.9.3p125 :025 > 
like image 149
Yanhao Avatar answered Nov 02 '22 18:11

Yanhao


People don't do this much, but Ruby's String class supports:

irb(main):002:0> str = 'car\\'
=> "car\\"
irb(main):003:0> str[/\\$/] = ''
=> ""
irb(main):004:0> str
=> "car"

It's a conditional search for a trailing '\', and replacement with an empty string.

like image 2
the Tin Man Avatar answered Nov 02 '22 19:11

the Tin Man


To remove a trailing backslash:

"car\\".gsub!(/\\$/, "")

Note that the backslash has to be escaped itself with a backslash.

like image 2
Sébastien Le Callonnec Avatar answered Nov 02 '22 19:11

Sébastien Le Callonnec