From: Calvin Bornhofen Date: 2013-04-19T03:14:42+09:00 Subject: Re: Match against multiple patterns problem Hello, there are two possible solutions coming to my mind: - Using the global $~, the last matched expression (equivalent to the return value of Regexp.last_match). This is not as good as the second idea imo, because you just get rid of the assignment, but your code is still as wet. - Since the pattern is "if match then return [something_changing, m[0]]", you could put all your regular expressions as well as the changing part in a hash and then loop through it. I think the second approach is better, since you avoid a lot of code duplication and it gets more maintainable (because you just have to modify the hash if you want to add/remove/modify one or more of your patterns and changing strings). It would look something like this: hsh = { /^[^\W_]+/ => "1", /^\s+/ )> "a" } s = s.to_s return ["1", ""] unless s.size >= 1 hsh.each do |regex, text| if regex =~ s return [text, Regexp.last_match 0] end end Hope this helps. Regards, Calvin On 18.04.2013 19:40, Charles Hixson wrote: > What I would want to do, if it were legal code would be: > if not s.is_a?(String) or len(s) < 1 then > return ["1",""] > if (m = /^[^\W_]+/.match(s) ) !== nil then return > ["a", m[0]] > elsif (m = /^\s+/.match(s) ) != nil then return > ["s", m[0]] > elsif (m = /^[[:cntrl:]]+/) != nil then return > ["c", m[0]] > elsif (m = /^[[:punct:]_]+/) != nil then return > ["p", m[0]] > elsif (m = /^[^\w\s[:cntrl:][:punct:]]+/) != nil > then return > ["r", m[0]] > But this isn't legal, because one can't do an assignment within a > logic test (any expression?). > So what SHOULD I do? I can double the length of the code by pulling > the assignments out, and > interleaving tests and assignments, but that's ugly (i.e., it makes > the code harder to read). Any better choices? >