Nekkoru Nekkoru - 1 year ago 84
Ruby Question

Multiple Ruby chomp! statements

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


The function has to return


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


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

The String class documentation says that
returns a
if modifications have been made - therefore, the second
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 Source

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


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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download