Regexp match and nil

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.

On Tue, Aug 26, 2008 at 9:29 AM, Adam A. [email protected]
wrote:

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.

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

From: Adam A. [mailto:[email protected]]

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.

try string#sub

0> class String
1> def remove_for_such_and_such
2> sub(%r{(.+)for.*}i){$1.strip}
2> end
1> end
=> nil

0> x=“fooforbar”
=> “fooforbar”

0> x.remove_for_such_and_such
=> “foo”

kind regards -botp