Reputation: 682
I'm trying to solve a Ruby problem using as less code as possible :). I want to check if a given string starts with a varying number of symbols, lets say between one and three 'a'. That's easy using reg exp, I can write string.match(\^a{1,3}.*\). But then I have to make changes on the string depending of the exact number of a's. How can I detect them without using three if's like that:
do_string_manipulation1 if string.match(/^a.*/)
do_string_manupulation2 if string.match(/^aa.*/)
...
Thanks in advance :)
Upvotes: 0
Views: 51
Reputation: 84140
Depends on what your string manipulations are.
You can determine the number of consecutive a's by doing:
string.match(/^(a{1,3}).*/)[1].size
You haven't defined the rules, so mine are:
"a" - downcase
"aa" - reverse
"aaa" - swapcase
So my code is:
string.send([:downcase, :reverse, :swapcase][string.match(/^(a{1,3}).*/)[1].size-1])
If your rules are more complicated, then you can define them as methods on a class and call them depending on the number returned.
Upvotes: 1
Reputation: 18430
Why not use a modified version of the first regexp and then simply count the a's it returns? A la
m = string.match(/^(a{1,3})/)
case m[1].size
when 1
when 2
when 3
end
Of course you can also use an array to store routines to call, depending on the number:
routines = [nil, method(:do_string_manipulation1), method(:do_string_manipulation2), ...]
routines[m[1].size].call
Upvotes: 1