vikas95prasad
vikas95prasad

Reputation: 1332

How to use gsub to remove . at the end of the string in ruby?

I need to remove all the special characters from the end of the string that sometimes will be there and sometimes not.

I have written this .gsub(/[,()'"]./,'') but it does not remove the . (full stop) from the string.

Can you tell me what is wrong in this?

Upvotes: 2

Views: 3063

Answers (2)

Robert Buchberger
Robert Buchberger

Reputation: 311

Does it have to be .gsub?

String#delete_suffix may be simpler.

my_string.delete_suffix '.'

Upvotes: 4

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

You may use

.gsub(/[,()'".]+\z/,'')

The dot must be put inside the character class, the negated character class must be quantified with + (1 or more occurrences) and the \z anchor should be added to assert the position at the end of the string.

See the Rubular demo.

Upvotes: 6

Related Questions