Reputation: 1478
This removes all spaces:
irb(main):021:0> 'gff gf ggfgfg '.gsub(' ','')
=> "gffgfggfgfg"
but I want just to remove the space at the end,
something like
irb(main):023:0> 'gff gf ggfgfg '.gsub([*' '$],'')
but I get:
SyntaxError: compile error
(irb):25: syntax error, unexpected $undefined, expecting ']'
'gff gf ggfgfg '.gsub([*' '$],'')
^
from (irb):25
from :0
^
(irb):23: syntax error, unexpected ',', expecting $end
'gff gf ggfgfg '.gsub(^' ','')
^
from (irb):23
from :0
n.b. I can't use truncate, trim and other rails helpers.
Upvotes: 1
Views: 7624
Reputation: 95252
There's also String#rstrip
, which isn't a Rails thing:
' foo bar '.rstrip # => " foo bar"
There's a self-modifying version rstrip!
, as well as lstrip
(!
) for leading space and strip
(!
) for both.
Upvotes: 6
Reputation: 156424
Use a regular expression which matches only whitespace at the end of the string:
'foo bar '.gsub(/\s+$/,'') # => "foo bar"
There is also rstrip
and rstrip!
:
'foo bar '.rstrip # => "foo bar"
Upvotes: 16