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

    Join Date
    Apr 2007
    Location
    Abertawe, Cymru
    Posts
    29
    Rep Power
    0

    Question Searching and replacing in a string based character occurence


    Hey,

    I have an IP address and I need to manipulate the final octet in a few different ways. For example,

    I have:

    Code:
    str = 10.100.100.0
    And I want to end up with:

    Code:
    newStr1 = 10.100.100.
    Code:
    newStr2 = 10.100.100.1
    Now the IP address length may vary so I can't spilt up on string length, I need to split up after the 3rd occurence of '.' .

    In PHP I'd use substr_replace but I can't find a Ruby equivilant.

    Any ideas?

    Thanks!
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2004
    Location
    Constant Limbo
    Posts
    989
    Rep Power
    363
    Code:
    irb(main):001:0> s = "10.1.1.1"
    => "10.1.1.1"
    irb(main):002:0> a = s.split '.'
    => ["10", "1", "1", "1"]
    irb(main):003:0> a
    => ["10", "1", "1", "1"]
    irb(main):004:0> a[3] = "200"
    => "200"
    irb(main):005:0> a.join '.'
    => "10.1.1.200"
    Or you can use ruby's 'intelligence' to your advantage:
    Code:
    irb(main):001:0> s = "10.1.1.1"
    => "10.1.1.1"
    irb(main):002:0> s.next
    => "10.1.1.2"
    True happiness is not getting what you want, it's wanting what you've already got.

    My Blog
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2007
    Location
    Abertawe, Cymru
    Posts
    29
    Rep Power
    0
    Split and Join work a treat! Thanks.

IMN logo majestic logo threadwatch logo seochat tools logo