How do I find if a string starts with another string in Ruby?

前端 未结 4 587
小鲜肉
小鲜肉 2020-12-13 08:02

What the best way to find if a string starts with another in Ruby (without rails)?

4条回答
  •  时光说笑
    2020-12-13 08:40

    Since there are several methods presented here, I wanted to figure out which one was fastest. Using Ruby 1.9.3p362:

    irb(main):001:0> require 'benchmark'
    => true
    irb(main):002:0> Benchmark.realtime { 1.upto(10000000) { "foobar"[/\Afoo/] }}
    => 12.477248
    irb(main):003:0> Benchmark.realtime { 1.upto(10000000) { "foobar" =~ /\Afoo/ }}
    => 9.593959
    irb(main):004:0> Benchmark.realtime { 1.upto(10000000) { "foobar"["foo"] }}
    => 9.086909
    irb(main):005:0> Benchmark.realtime { 1.upto(10000000) { "foobar".start_with?("foo") }}
    => 6.973697
    

    So it looks like start_with? ist the fastest of the bunch.

    Updated results with Ruby 2.2.2p95 and a newer machine:

    require 'benchmark'
    Benchmark.bm do |x|
      x.report('regex[]')    { 10000000.times { "foobar"[/\Afoo/] }}
      x.report('regex')      { 10000000.times { "foobar" =~ /\Afoo/ }}
      x.report('[]')         { 10000000.times { "foobar"["foo"] }}
      x.report('start_with') { 10000000.times { "foobar".start_with?("foo") }}
    end
    
                user       system     total       real
    regex[]     4.020000   0.000000   4.020000 (  4.024469)
    regex       3.160000   0.000000   3.160000 (  3.159543)
    []          2.930000   0.000000   2.930000 (  2.931889)
    start_with  2.010000   0.000000   2.010000 (  2.008162)
    

提交回复
热议问题