regexp match and nil

A

Adam Akhtar

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.
 
J

Jesús Gabriel y Galán

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.
 
A

Adam Akhtar

thanks guys.. ill look into sub as well...couldnt tell what would happen
there if it didnt match but looks interesting.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top