Forum: Ruby String#starts_with?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ae16cb4f6d78e485b04ce1e821592ae5?d=identicon&s=25 Martin DeMello (Guest)
on 2006-07-08 19:57
(Received via mailing list)
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
14c657815683cad8a59e299c625c93c3?d=identicon&s=25 Marcin MielżyÅ?ski (Guest)
on 2006-07-08 21:14
(Received via mailing list)
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
Ae16cb4f6d78e485b04ce1e821592ae5?d=identicon&s=25 Martin DeMello (Guest)
on 2006-07-08 21:18
(Received via mailing list)
On 7/9/06, Marcin Miel¿yñski <lopx@gazeta.pl> wrote:
> 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

thanks. any suggestions for #ends_with?

martin
Cd49db0b676767ea4358b1047c4cddd2?d=identicon&s=25 Robin Stocker (Guest)
on 2006-07-08 21:25
(Received via mailing list)
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
Cd49db0b676767ea4358b1047c4cddd2?d=identicon&s=25 Robin Stocker (Guest)
on 2006-07-08 21:32
(Received via mailing list)
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
This topic is locked and can not be replied to.