seaneshbaugh seaneshbaugh - 3 months ago 9
Ruby Question

Removing a pattern from the beginning and end of a string in ruby

So I found myself needing to remove

<br />
tags from the beginning and end of strings in a project I'm working on. I made a quick little method that does what I need it to do but I'm not convinced it's the best way to go about doing this sort of thing. I suspect there's probably a handy regular expression I can use to do it in only a couple of lines. Here's what I got:

def remove_breaks(text)
if text != nil and text != ""
text.strip!

index = text.rindex("<br />")

while index != nil and index == text.length - 6
text = text[0, text.length - 6]

text.strip!

index = text.rindex("<br />")
end

text.strip!

index = text.index("<br />")

while index != nil and index == 0
text = test[6, text.length]

text.strip!

index = text.index("<br />")
end
end

return text
end


Now the
"<br />"
could really be anything, and it'd probably be more useful to make a general use function that takes as an argument the string that needs to be stripped from the beginning and end.

I'm open to any suggestions on how to make this cleaner because this just seems like it can be improved.

fgb fgb
Answer

gsub can take a regular expression:

text.gsub!(/(<br \/>\s*)*$/, '')
text.gsub!(/^(\s*<br \/>)*/, '')
text.strip!