gpt4 book ai didi

ruby - 检查字符串变量是否在一组字符串中

转载 作者:数据小太阳 更新时间:2023-10-29 07:04:04 38 4
gpt4 key购买 nike

哪个更好:

x == 'abc' || x == 'def' || x == 'ghi'
%w(abc def ghi).include? x
x =~ /abc|def|ghi/

?

最佳答案

哪个更好?这个问题不容易回答,因为他们做的事情不尽相同。

x == 'abc' || x == 'def' || x == 'ghi'
%w(abc def ghi).include? x

比较 x 与固定字符串是否相等。 x 必须是这些值之一。在这两者之间,我倾向于选择第二个,因为它更容易维护。想象一下,如果您必须与 20、50 或 100 个字符串进行比较会是什么样子。

第三个测试:

x ~= /abc|def|ghi/

匹配子串:

x = 'xyzghi'
(x =~ /abc|def|ghi/) # => 3

所以它与前两个不同。

编辑:在 nash 完成的基准测试中,我会做一些不同的事情。在 MacBook Pro 上使用 Ruby 1.9.2-p180,这测试了 1,000,000 次循环并比较了锚定正则表达式、使用分组以及每次在循环中不拆分 %w() 数组的结果:

require 'benchmark'
str = "test"

n = 1_000_000
Benchmark.bm do |x|
x.report { n.times { str == 'abc' || str == 'def' || str == 'ghi' } }
x.report { n.times { %w(abc def ghi).include? str } }
x.report { ary = %w(abc def ghi); n.times { ary.include? str } }
x.report { n.times { str =~ /abc|def|ghi/ } }
x.report { n.times { str =~ /^abc|def|ghi$/ } }
x.report { n.times { str =~ /^(abc|def|ghi)$/ } }
x.report { n.times { str =~ /^(?:abc|def|ghi)$/ } }
x.report { n.times { str =~ /\b(?:abc|def|ghi)\b/ } }
end
# >> user system total real
# >> 1.160000 0.000000 1.160000 ( 1.165331)
# >> 1.920000 0.000000 1.920000 ( 1.920120)
# >> 0.990000 0.000000 0.990000 ( 0.983921)
# >> 1.070000 0.000000 1.070000 ( 1.068140)
# >> 1.050000 0.010000 1.060000 ( 1.054852)
# >> 1.060000 0.000000 1.060000 ( 1.063909)
# >> 1.060000 0.000000 1.060000 ( 1.050813)
# >> 1.050000 0.000000 1.050000 ( 1.056147)

关于ruby - 检查字符串变量是否在一组字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5280810/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com