Ruby:布尔正则表达式方法的正确语法是什么? [英] Ruby: What's the proper syntax for a boolean regex method?
本文介绍了Ruby:布尔正则表达式方法的正确语法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
检查字符串中的模式并在正则表达式匹配时返回 true 或 false 的方法的正确语法是什么?
What is the proper syntax for a method that checks a string for a pattern, and returns true or false if the regex matches?
基本思路:
def has_regex?(string)
pattern = /something/i
return string =~ pattern
end
用例:
if has_regex?("something")
# woohoo
else
# nothing found: panic!
end
推荐答案
如果你想把模式放在一个方法中,你可以这样做
If you want the put the pattern in a method, you can just do
def has_my_pattern(st)
st =~ /pattern/
end
或者,也许更好,将模式放在类变量中?
Or, perhaps better, put the pattern in a class variable instead?
这篇关于Ruby:布尔正则表达式方法的正确语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文