0

For a field name I have several regexps that made some change to field if it matches.

Right now here is what I'm doing in psuedocode:

if (name matches regexp1)
  make change1 to name
elsif (name matches regexp2)
  make change2 to name
elsif (name matches regexp3)
  make change3 to name

I have over 20 of such things to check. Is there a better way to code this?

Jacob
  • 6,317
  • 10
  • 40
  • 58
  • 1
    Do you always do change1 in each branch? Or is it just a typo? If not, you can put all regexps into a list, validate `name` vs each item in the list (using a loop construct), and as soon as one matches, do the change and leave the loop. – Tim Meyer Nov 15 '11 at 12:30
  • That was a typo :) Thanks your solution would be cleaner (put regexp and replacements in a hash first) – Jacob Nov 15 '11 at 12:35
  • If you simply replace the name, you can use a hash map indeed. – Tim Meyer Nov 15 '11 at 12:37
  • Related question: http://stackoverflow.com/questions/8132492/ruby-multiple-string-replacement – nathanvda Nov 15 '11 at 12:46
  • @nathanvda Would this work for the entire string replacement though (I'm not looking to replace part of a string) -- i.e. I'm going to replace the whole original strong using extracts parts of it. – Jacob Nov 15 '11 at 13:00
  • Ah. That was not entirely clear to me. My bad. – nathanvda Nov 15 '11 at 13:15
  • My personal preference would be to utilize a case statement rather than have a bunch of if / else's. This also allows you to easily match against multiple regexps and perform a single action. – mnelson Nov 15 '11 at 23:24

1 Answers1

0

I'd do it like so

change1(name) if name.match(/some_regex_one/)
change2(name) if name.match(/some_regex_two/)
change3(name) if name.match(/some_regex_three/)

That way you can still easily scan to see all your 20 different regexs and changes that go along with them.

Might not be the most efficient way but it's possibly the most readable way.

Dty
  • 12,253
  • 6
  • 43
  • 61