在Ruby(不使用Rails)中查找字符串是否以另一个字符串开头的最佳方式是什么?
在Ruby(不使用Rails)中查找字符串是否以另一个字符串开头的最佳方式是什么?
puts 'abcdefg'.start_with?('abc') #=> true
[编辑] 在回答这个问题之前我不知道的一件事是:start_with?
可以接受多个参数。
'abcdefg'.start_with?( 'xyz', 'opq', 'ab')
start_with?
方法,但是 MRI 1.9 和 Rails 都有。 - Wayne Conradstart_with?
。我猜我在加载irb尝试时打错了。 - Wayne Conradstarts_with?
方法,在 1.8.7 及以上版本中它被别名为 start_with?
。 - Mark Thomas因为在这里提出了几种方法,我想弄清哪一种是最快的。使用 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
看起来 start_with?
是这一组中最快的。
在 Ruby 2.2.2p95 和更新的机器上进行了更新的结果:
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)
start_with?
函数仍然是最佳选择,只需将要搜索的字符串转换成小写字母后再与小写字母的搜索字符串进行比较即可:"FooBar".downcase.start_with?("foo")
。 - haslo'abcdefg' =~ /\Aabc/
I like
if ('string'[/^str/]) ...
[/\Astr/]
。你的正则表达式也匹配了 "another\nstring"
。 - haslo