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

前端 未结 4 588
小鲜肉
小鲜肉 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:19
    puts 'abcdefg'.start_with?('abc')  #=> true
    

    [edit] This is something I didn't know before this question: start_with takes multiple arguments.

    'abcdefg'.start_with?( 'xyz', 'opq', 'ab')
    
    0 讨论(0)
  • 2020-12-13 08:30

    The method mentioned by steenslag is terse, and given the scope of the question it should be considered the correct answer. However it is also worth knowing that this can be achieved with a regular expression, which if you aren't already familiar with in Ruby, is an important skill to learn.

    Have a play with Rubular: http://rubular.com/

    But in this case, the following ruby statement will return true if the string on the left starts with 'abc'. The \A in the regex literal on the right means 'the beginning of the string'. Have a play with rubular - it will become clear how things work.

    'abcdefg' =~  /\Aabc/ 
    
    0 讨论(0)
  • 2020-12-13 08:31

    I like

    if ('string'[/^str/]) ...
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题