From: Matthew Kerwin Date: 2013-04-19T12:08:35+09:00 Subject: Re: Match against multiple patterns problem Charles Hixson wrote in [#1106215]: > The case expression might be a bit cleaner, but that would appear to > coerce using the $~ pattern match value, which I don't like at all $~ is the same object as your 'm', so you can do your `m[0]' thing with it, or call `m.to_s' on it, or whatever you like to explicitly coerce it. I'll put some examples below. > The current version is: > if not s.is_a?(String) or s.length < 1 then return ["1",""] > if (m = /^[^\W_]+/.match(s) ) then return ["a", m[0]] > if (m = /^\s+/.match(s) ) then return ["s", m[0]] > if (m = /^[[:cntrl:]]+/) then return ["c", m[0]] > if (m = /^[[:punct:]_]+/) then return ["p", m[0]] > if (m = /^[^\w\s[:cntrl:][:punct:]]+/) != nil > then return ["r", m[0]] > which looks a lot better. Sure, except that it's syntactically invalid (missing all the 'end's) and the final 3 if-statements assign the regexp (not the match data) to m. Hopefully this is just a copy-paste error; otherwise, decent unit tests should catch it. > Also, there would need to be a default case to handle uncovered > options (which just prints an error message and returns ["2", ""]. Your original (and final) code missed that part. If you want to not assign m in the condition, you could use $~. Here's a straight copy of your final code (with some fixes): if !s.is_a?(String) or s.length < 1 then return ["1",""]; end if /^[^\W_]+/.match(s) then return ["a", $~[0]]; end if /^\s+/.match(s) then return ["s", $~[0]]; end if /^[[:cntrl:]]+/.match(s) then return ["c", $~[0]]; end if /^[[:punct:]_]+/.match(s) then return ["p", $~[0]]; end if /^[^\w\s[:cntrl:][:punct:]]+/.match(s) then return ["r", $~[0]]; end puts "error message" ["2",""] Or with a case statement: return ['1',''] unless s.is_a?(String) and !s.empty? case s when /^[^\W_]+/ ; ['a', $~[0]] when /^\s+/ ; ['s', $~[0]] when /^[[:cntrl:]]+/ ; ['c', $~[0]] when /^[[:punct:]_]+/ ; ['p', $~[0]] when /^[^\w\s[:cntrl:][:punct:]]+/ ['r', $~[0]] else puts "error message" ['2', ''] end Obviously you can arrange it however you like, I've just attempted to match your layout style based on a guess. Charles Hixson wrote in [#1106217]: > Given that $1 means what I think it means from context, that would work, > but I dislike the global variables with pattern matching. The global assignment happens whether or not you like/use it. Assertively not using the feature isn't a very strong way to express your displeasure with it, and it won't just shrivel up and drop off lack of use. ;) See also: https://bugs.ruby-lang.org/issues/8110 > But really my problem was being mislead by error messages about what the > problem actually was. That is the main thing. As a tip, in future you should include the error message in your post; possibly someone with more experience could help you find the root cause more quickly that way. -- Posted via http://www.ruby-forum.com/.