Thomas Swift

Running a West Coast Offense since ‘81

Ruby String Replace

March 22nd, 2007 · 3 Comments

update: I noticed I am dominating google searches for “ruby string replace”, if you have a particular example you are looking for or snippet you might need some help with, feel free to leave a comment or drop me an email and i’ll try to help you.

I just want to replace [width=”ANYNUMBER] with [width=”300] and [height=”ANYNUMBER] with [height=”243] (brackets for visual clarity)


embed_src = "" #biglong youtube embed link
w = 300
h = 243
#gsub expects strings not integers, so i used a to_s
embed_src = embed_src.gsub(/width="d+/,'width="'<

I wrapped this into a simple helper function so i can call it over and over again.

Tags: ruby

3 responses so far ↓

  • 1 Danny // Apr 18, 2007 at 6:42 am

    I have a simple question, which I haven’t found the answer to thusfar. I am working on a database migration script and want to replace every text column that features double quotation marks anywhere in data with single quotation marks. I know it must be simple, just can’t figure it out…

  • 2 Thomas Swift // Apr 18, 2007 at 12:41 pm

    this might not be the most optimized way of doing it, but you can use gsub! like this

    #remove exclamation if you don’t want the substitution to happen in place

    open up irb and try this

    
    a= 'this is a "test" dataset '
    a.gsub!(/"/,'\'')
    puts a # gives us ->   this is a 'test' dataset
    

    may be that helps

  • 3 Danny // May 11, 2007 at 9:40 am

    Hey, I know I am shamelessly late, while your reply was so fast, busy, busy you know…

    In the end the following did the trick:

    query = %(INSERT INTO(blabla) VALUES(”#{@mysql.quote key[’value’] if key[’value’]}”);)

    @mysql.query query

    thanks very much anyway :)

Leave a Comment