String#starts_with?

Discussion in 'Ruby' started by Martin DeMello, Jul 8, 2006.

  1. Has anyone run tests to see what the fastest way to do a
    String#starts_with?(otherstring) is? I'll need this in an inner loop,
    so it's worth squeezing out the few drops of extra speed.

    martin
     
    Martin DeMello, Jul 8, 2006
    #1
    1. Advertising

  2. Martin DeMello wrote:
    > Has anyone run tests to see what the fastest way to do a
    > String#starts_with?(otherstring) is? I'll need this in an inner loop,
    > so it's worth squeezing out the few drops of extra speed.



    String#index should be the fastest

    lopex
     
    Marcin Mielżyński, Jul 8, 2006
    #2
    1. Advertising

  3. Marcin Mielżyński wrote:
    > String#index should be the fastest


    I'm afraid it isn't suitable for this case. String#index searches the
    whole string when the string doesn't start with the start, which is very
    bad.

    Use String#[] or a regular expression:

    text = "this is a test"
    search = "this"
    text[0, search.length] == search #=> true

    text =~ /^this/ #=> 0 (true)
    text =~ /^test/ #=> nil (false)

    Cheers,
    Robin Stocker
     
    Robin Stocker, Jul 8, 2006
    #3
  4. Martin DeMello wrote:
    > thanks. any suggestions for #ends_with?


    Yes, two examples:

    "this is a test" =~ /test$/ #=> 10 (true)

    text = "this is a test"
    search = "test"
    text[text.length - search.length, search.length] == search #=> true
     
    Robin Stocker, Jul 8, 2006
    #4
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Mladen Adamovic
    Replies:
    0
    Views:
    738
    Mladen Adamovic
    Dec 4, 2003
  2. Mladen Adamovic
    Replies:
    3
    Views:
    14,613
    Mladen Adamovic
    Dec 5, 2003
  3. Matt
    Replies:
    3
    Views:
    508
    Tor Iver Wilhelmsen
    Sep 17, 2004
  4. Bruce Sam
    Replies:
    15
    Views:
    7,931
    John C. Bollinger
    Nov 19, 2004
  5. Skave Rat

    problem with "starts_with?"

    Skave Rat, Aug 1, 2008, in forum: Ruby
    Replies:
    5
    Views:
    88
    matt neuburg
    Aug 1, 2008
Loading...

Share This Page