在Ruby(没有rails)中查找字符串是否以另一个开头的最佳方法是什么?
问问题
114162 次
4 回答
289
puts 'abcdefg'.start_with?('abc') #=> true
[编辑] 这是我在这个问题之前不知道的:start_with
接受多个参数。
'abcdefg'.start_with?( 'xyz', 'opq', 'ab')
于 2010-11-12T20:02:23.160 回答
61
由于这里介绍了几种方法,我想找出哪一种最快。使用 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)
于 2013-01-11T09:55:08.053 回答
5
steenslag 提到的方法很简洁,考虑到问题的范围,它应该被认为是正确的答案。然而,同样值得知道的是,这可以通过正则表达式来实现,如果您还不熟悉 Ruby,这是一项重要的学习技能。
玩一下 Rubular:http: //rubular.com/
但在这种情况下,如果左边的字符串以 'abc' 开头,则以下 ruby 语句将返回 true。右侧正则表达式文字中的 \A 表示“字符串的开头”。玩一下rubular - 它会变得很清楚事情是如何运作的。
'abcdefg' =~ /\Aabc/
于 2010-11-12T20:20:39.487 回答
2
我喜欢
if ('string'[/^str/]) ...
于 2010-11-12T23:19:46.053 回答