String#starts_with?

M

Martin DeMello

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
 
M

Marcin Mielżyński

Martin said:
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
 
R

Robin Stocker

Marcin said:
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
 
R

Robin Stocker

Martin said:
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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top