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

Posted by seaneshbaugh on Stack Overflow See other posts from Stack Overflow or by seaneshbaugh
Published on 2010-04-30T09:35:51Z Indexed on 2010/04/30 10:07 UTC
Read the original article Hit count: 240

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.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about ruby-on-rails