Nekkoru Nekkoru - 5 months ago 7
Ruby Question

Multiple Ruby chomp! statements

I'm writing a simple method to detect and strip tags from text strings. Given this input string:

{{foobar}}


The function has to return

foobar


I thought I could just chain multiple
chomp!
methods, like so:

"{{foobar}}".chomp!("{{").chomp!("}}")


but this won't work, because the first
chomp!
returns a
NilClass
. I can do it with regular
chomp
statements, but I'm really looking for a one-line solution.

The String class documentation says that
chomp!
returns a
Str
if modifications have been made - therefore, the second
chomp!
should work. It doesn't, however. I'm at a loss at what's happening here.

For the purposes of this question, you can assume that the input string is always a tag which begins and ends with double curly braces.

Answer

You can definitely chain multiple chomp statements (the non-bang version), still having a one-line solution as you wanted:

 "{{foobar}}".chomp("{{").chomp("}}")

However, it will not work as expected because both chomp! and chomp removes the separator only from the end of the string, not from the beginning.

You can use sub

"{{foobar}}".sub(/{{(.+)}}/, '\1')
# => "foobar"

"alfa {{foobar}} beta".sub(/{{(.+)}}/, '\1')
# => "alfa foobar beta"

# more restrictive
"{{foobar}}".sub(/^{{(.+)}}$/, '\1')
# => "foobar"