Hi --

On Tue, 21 Aug 2007, William James wrote:

> On Aug 20, 4:40 pm, Phrogz <phr... / mac.com> wrote:
>> On Aug 20, 3:32 pm, William James <w_a_x_... / yahoo.com> wrote:
>>
>>> On Aug 20, 2:44 pm, Ari Brown <a... / aribrown.com> wrote:
>>>> How do named captures in Ruby work? This is what I've tried:
>>> A work-around:
>>
>>> md = "foo bar".match( /(\w+) (\w+)/ )
>>>     ==>#<MatchData:0x2851ef0>
>>> name, surname = md.captures
>>>     ==>["foo", "bar"]
>>> name
>>>     ==>"foo"
>>> surname
>>>     ==>"bar"
>>
>> Or my favorite (courtesy of Ara):
>>
>> _, name, surname = /(\w+) (\w+)/.match("foo bar").to_a
>
> name, surname = /(\w+) (\w+)/.match("foo bar").captures

That has the disadvantage that it will blow up if the match fails (no
captures method for nil).


David

-- 
* Books:
   RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242)
   RUBY FOR RAILS (http://www.manning.com/black)
* Ruby/Rails training
     & consulting:  Ruby Power and Light, LLC (http://www.rubypal.com)