在字符串的开头找到给定符号的确切数字
问题描述:
我试图用尽可能少的代码来解决Ruby问题:)。我想检查给定的字符串是否以不同数量的符号开始,可以说一到三个'a'。这很容易使用reg exp,我可以写string.match(\^a {1,3}。* \)。但是,我必须根据a的确切数量对字符串进行更改。我怎样才能检测到它们,而不使用三个IF的那样:在字符串的开头找到给定符号的确切数字
do_string_manipulation1 if string.match(/^a.*/)
do_string_manupulation2 if string.match(/^aa.*/)
...
感谢提前:)
答
为什么不使用正则表达式第一个修改版本,然后简单地算一个是它返回?一拉
m = string.match(/^(a{1,3})/)
case m[1].size
when 1
when 2
when 3
end
当然,你也可以使用一个数组来存储程序调用,取决于数量:
routines = [nil, method(:do_string_manipulation1), method(:do_string_manipulation2), ...]
routines[m[1].size].call
答
取决于你的字符串操作是什么。
您可以通过执行确定连续一个的数量:
string.match(/^(a{1,3}).*/)[1].size
您还没有定义的规则,所以我的是:
"a" - downcase
"aa" - reverse
"aaa" - swapcase
所以我的代码是:
string.send([:downcase, :reverse, :swapcase][string.match(/^(a{1,3}).*/)[1].size-1])
如果你的规则更加复杂,那么你可以将它们定义为一个类的方法并根据这个方法调用它们电话号码返回。
非常感谢。我不知道'匹配'返回什么 – mjekov
MatchData对象,如下所述:http://rubydoc.info/stdlib/core/1.9.3/MatchData –
或者,您可以使用=〜运算符,然后访问全局变量$ 1(在这种情况下,通常它是$ 1 .. $ n)。这样做的好处是速度更快,因为它不必创建MatchData对象。 –