从ruby中的字符串的开头和结尾删除模式

sea*_*ugh 4 ruby string refactoring ruby-on-rails

所以我发现自己需要<br />在我正在处理的项目中从字符串的开头和结尾删除标签.我做了一个快速的小方法来完成我需要做的事情,但我不相信这是做这类事情的最好方法.我怀疑可能有一个方便的正则表达式,我可以用它来做几行.这是我得到的:

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
Run Code Online (Sandbox Code Playgroud)

现在"<br />"可能真的是任何东西,并且制作一个通用的函数可能更有用,该函数将需要从开头和结尾剥离的字符串作为参数.

我对如何使这个更清洁的任何建议持开放态度,因为这似乎可以改进.

fgb*_*fgb 9

gsub可以采用正则表达式:

text.gsub!(/(<br \/>\s*)*$/, '')
text.gsub!(/^(\s*<br \/>)*/, '')
text.strip!
Run Code Online (Sandbox Code Playgroud)