[英]String includes another string or regex (Ruby)
I need to check if given String includes a string or regex. 我需要检查给定的String是否包含字符串或正则表达式。 If it does, it should return true, otherwise - false.
如果是这样,则应返回true,否则返回false。 How can I do it?
我该怎么做?
I have: 我有:
def method(string)
if @text.match(/#{string}/)
true
else
false
end
end
But I'm not sure if it's a proper way. 但是我不确定这是否是正确的方法。
Consider this: 考虑一下:
@text = 'foobar'
def method1(string)
if @text.match(/#{string}/)
true
else
false
end
end
That can be reduced to: 可以简化为:
def method2(string_or_regex)
if @text[string_or_regex]
true
else
false
end
end
String's []
method allows us to pass in a string or a pattern. String的
[]
方法允许我们传入字符串或模式。 If it's a string, the method uses it for a fixed-string/in-string search. 如果是字符串,则该方法将其用于固定字符串/字符串内搜索。 If a pattern is passed in it returns the matching text.
如果传入模式,则返回匹配的文本。
However, Ruby is more friendly than this. 但是,Ruby比这更友好。 We don't have to tell it to return a true or false value conditionally.
我们不必告诉它有条件地返回true或false值。 In Ruby, a nil or
false
value is treated as false, and anything else is "truethy". 在Ruby中,nil或
false
值被视为false,其他任何东西都是“ truethy”。 We can convert a value to true/false using !!
我们可以使用
!!
将值转换为true / false !!
, which is double boolean "not": ,这是双重布尔值“ not”:
true # => true
'foo' # => "foo"
false # => false
nil # => nil
!true # => false
!'foo' # => false
!false # => true
!nil # => true
!!true # => true
!!'foo' # => true
!!false # => false
!!nil # => false
Knowing that, and that String's []
returns a nil if not found, or the matching text if found: 知道这一点,并且String的
[]
如果找不到则返回nil,或者如果找到则返回匹配的文本:
'foo'['foo'] # => "foo"
'foo'['bar'] # => nil
we can reduce the original method to: 我们可以将原始方法简化为:
def method3(string_or_regex)
!!@text[string_or_regex]
end
Here's what happens testing each of the methods above: 这是测试上述每种方法的结果:
method1('foo') # => true
method1('baz') # => false
method2('foo') # => true
method2(/foo/) # => true
method2('baz') # => false
method2(/baz/) # => false
method3('foo') # => true
method3(/foo/) # => true
method3('baz') # => false
method3(/baz/) # => false
You have to be careful interpolating a regular expression object into another regular expression: 您必须小心将正则表达式对象插入另一个正则表达式:
string = /foo/
/#{string/ # => /(?-mix:foo)/
The (?-mix:
are the pattern flags being inserted inside another pattern, which can open your pattern to all sorts of weird behaviors and create extremely hard to find bugs. Instead, I strongly recommend using the source
method if you're going to do that, which results in the original pattern being inserted: (?-mix:
是将模式标志插入到另一个模式中,该模式标志可以将您的模式打开到各种奇怪的行为,并且极难发现错误。相反,强烈建议您使用source
方法这样做,将导致插入原始模式:
/#{string.source}/ # => /foo/
单行代码:
!@text.match(/#{string}/).nil?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.