#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2006
    Posts
    326
    Rep Power
    9

    Regular Expressions In Ruby?


    I'm reading a book on Ruby, and I just started a little while ago. I have gotten some decent ground and they just introduced Regular Expressions, but for some reason I can't get them to work. Take this code for example:

    Code:
    line = "Perl"
    line.sub(/Perl/, 'Ruby')
    puts line
    When I run the code I still see "Perl" getting printed to the string when it should have replaced it with "Ruby". Also, when I do stuff like:

    Code:
    line = "Yes I like Ruby"
    if line =~ /Ruby/
        puts line
    end
    Instead of printing the index of where the expression starts (like the book says) it just prints out the string again.

    Am I doing something wrong?

    Cheers,
    ~ Alias
  2. #2
  3. (retired)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 2003
    Location
    The Laboratory
    Posts
    10,101
    Rep Power
    0
    Moved to the brand new "Ruby Programming" forum
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2004
    Posts
    394
    Rep Power
    52
    Hi!

    2 solutions:
    Ruby Code:
    line = "Perl"
    newline = line.sub(/Perl/, "Ruby")
    # or
    line.sub!(/Perl/, "Ruby")

    line.sub() does not change the original line, line.sub! does.
    This is very common in Ruby, other examples are
    Code:
    chomp  --- chomp!
    chop --- chop!
    strip --- strip!
    ...
    Regards, mawe

    Comments on this post

    • AliasXNeo agrees : Thanks for the nice help! :) ~ AliasXNeo
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2006
    Posts
    326
    Rep Power
    9
    Wow, cleared it up perfectly. Thanks a lot!

    Cheers,
    ~ Alias

IMN logo majestic logo threadwatch logo seochat tools logo