From: Carlos Date: 2004-07-07T21:49:27+09:00 Subject: Re: Regexp exercise ["Olivier D." , 2004-07-07 14.37 CEST] > Hi, > I have a string from which I want to extract a value. I have found four > different methods to do it: > > string = "a: 1, b: 2, c: 3" > # let's say I want the value associated with b (2) > > # 1st method: > value = string[/b: \d+/][/\d+/] > > # 2nd method: > value = string.scan(/b: (\d+)/)[0][0] > > # 3rd method: > value = nil > string.scan(/b: (\d+)/) { |val| value = val } > > These three methods aren't clean and easy to understand. > > I think that the best way to do it would be to use a simple match > operator like: > value = $1 if string =~ /b: (\d+)/ > > But on a different thread (http://tinyurl.com/38b27) someone explained > that using global variables was a bad habit not to take. > > What should I do? Is the $1 method *that* bad? (after all, I just use it > inside the 'if' loop...) I don't find it bad, but if you want to avoid it you can do matchdata=/b: (\d+)/.match(string) and value=matchdata[1]