Jesús Gabriel y Galán
8/26/2008 7:47:00 AM
On Tue, Aug 26, 2008 at 9:29 AM, Adam Akhtar <adamtemporary@gmail.com> wrote:
> heres my function
>
> def remove_for_such_and_such(a_string)
> if (%r{(.+)for.*}i =~ a_string)
> match = a_string.match(%r{(.+)for.*}i)
> a_string = match[1].strip
> end
> a_string
> end
>
> i want to know if that could be written better. I wrote the if clause
> because sometimes a string may not match the regular expression. If i
> remove the "if" clause it might lead to match returning nil which will
> stop my program. Im wondring is there a way to avoid using if?? if so it
> could help performance especially if this function was used with huge
> arrays of strings.
With your above code you are trying to match the regexp twice:
one for the =~ and one for the match, which is not optimal. I would
do it like this:
def remove_for_such_and_such(a_string)
m = a_string.match(%r{(.+)for.*}i)
a_string = m[1].strip if m
a_string
end
Anyway you need an if, because you need to know if the string matched or not.
If you want to avoid using if at all costs, you can play with rescue,
but I think
it's not as clear as checking explicitly. YMMV.
Jesus.