Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > String#starts_with?

Reply
Thread Tools

String#starts_with?

 
 
Martin DeMello
Guest
Posts: n/a
 
      07-08-2006
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

 
Reply With Quote
 
 
 
 
Marcin Mielżyński
Guest
Posts: n/a
 
      07-08-2006
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
 
Reply With Quote
 
 
 
 
Robin Stocker
Guest
Posts: n/a
 
      07-08-2006
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

 
Reply With Quote
 
Robin Stocker
Guest
Posts: n/a
 
      07-08-2006
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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off




Advertisments