From: "Jesús Gabriel y Galán" Date: 2013-04-19T03:09:23+09:00 Subject: Re: Match against multiple patterns problem On Thu, Apr 18, 2013 at 7:40 PM, 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? Actually you can do assignments inside logical expressions. The problems in the code above are related to nonexistent methods (len), operator precedence(not and or) and a typo (!==). Try this: if (!s.is_a?(String) || (s.length < 1)) return ["1",""] end 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]] end Changing the returns for puts to test outside a method: 1.9.2p290 :116 > s = " " => " " 1.9.2p290 :117 > if (!s.is_a?(String) || (s.length < 1)) 1.9.2p290 :118?> puts ["1",""] 1.9.2p290 :119?> end => nil 1.9.2p290 :120 > if (m = /^[^\W_]+/.match(s) ) != nil then puts ["a", m[0]] 1.9.2p290 :121?> elsif (m = /^\s+/.match(s) ) != nil then puts ["s", m[0]] 1.9.2p290 :122?> elsif (m = /^[[:cntrl:]]+/) != nil then puts ["c", m[0]] 1.9.2p290 :123?> elsif (m = /^[[:punct:]_]+/) != nil then puts ["p", m[0]] 1.9.2p290 :124?> elsif (m = /^[^\w\s[:cntrl:][:punct:]]+/) != nil then puts ["r", m[0]] 1.9.2p290 :125?> end s It's not very pretty still, but at least it works. I'm sure someone will come up with a more elegant solution. Jesus.