检查字符串中的模式并在正则表达式匹配时返回 true 或 false 的方法的正确语法是什么?
基本思路:
def has_regex?(string)
pattern = /something/i
return string =~ pattern
end
用例:
if has_regex?("something")
# woohoo
else
# nothing found: panic!
end
最佳答案
在你说的问题中:
... method that checks a string for a pattern, and returns true or false if the regex matches
作为johannes指出String=~
如果模式不匹配则返回 nil
,否则返回匹配单词在字符串中的位置。此外,他在 Ruby 中声明了除 nil
和 false
behave like true
之外的所有内容。这一切都是对的。
但是,它们不完全是 true
或false
。因此,最后一步是将该值强制为 Boolean
。这是通过将结果包裹在双刘海中返回 true
来实现的。
def has_regex?(string)
!!(string =~ /something/i)
end
关于Ruby: bool 正则表达式方法的正确语法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2215303/