From: "David A. Black" Date: 2004-07-07T22:25:39+09:00 Subject: Re: Regexp exercise Hi -- On Wed, 7 Jul 2004, Olivier D. wrote: > 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+)/ In addition to the other answers, if you want to grab the value as an integer, you could do: require 'scanf' str = "a: 1, b: 2, c: 3" val, = str.scanf("%*[^b]b: %d") p val # => 2 David -- David A. Black dblack@wobblini.net