From: Florian Frank Date: 2002-08-29T22:46:16+09:00 Subject: Re: Newbie converting brain from perl --=-m82svbvaD7u2IgR4djuV Content-Type: text/plain Content-Transfer-Encoding: 7bit On Wed, 2002-08-28 at 22:31, William Pietri wrote: > > Howdy! As a long time Perl, Java, and Objective-C developer, I'm quite taken > with Ruby, and I'm busily converting my brain over. But there's a Perl > idiom that I'm having trouble translating. In Perl it goes like this: > > $date = "28 Aug 2002"; > ($day, $month, $year) = $date =~ /(\d+) (\w+) (\d+)/; > > > In Ruby the best I've been able to do is this: > > date = "28 Aug 2002" > day, month, year = /(\d+) (\w+) (\d+)/.match(date)[1..3] > > But that final [1..3] thing seems inelegant, which makes me think I'm > barking up the wrong tree. What's the best Ruby-style way to do this? I stumbled over this problem before. I think there isn't a really elegant solution for this right now. Adding MatchDate#captures to ruby would be possible though without breaking much existing code: /(\d+) (\w+) (\d+)/.match("28 Aug 2002").captures ==>["28", "Aug", "2002"] I've made a little patch for this behaviour (attachment). -- There is no God, and Murphy is his prophet. --=-m82svbvaD7u2IgR4djuV Content-Disposition: attachment; filename=re-captures.patch Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; name=re-captures.patch; charset=ISO-8859-15 Index: re.c =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D RCS file: /src/ruby/re.c,v retrieving revision 1.78 diff -u -r1.78 re.c --- re.c 2002/08/29 09:08:16 1.78 +++ re.c 2002/08/29 13:19:57 @@ -898,6 +898,15 @@ } =20 static VALUE +match_captures(match) + VALUE match; +{ + VALUE ary =3D match_to_a(match); + rb_ary_shift(ary); + return ary; +} + +static VALUE match_aref(argc, argv, match) int argc; VALUE *argv; @@ -1615,6 +1624,7 @@ rb_define_method(rb_cMatch, "end", match_end, 1); rb_define_method(rb_cMatch, "to_a", match_to_a, 0); rb_define_method(rb_cMatch, "to_ary", match_to_a, 0); + rb_define_method(rb_cMatch, "captures", match_captures, 0); rb_define_method(rb_cMatch, "[]", match_aref, -1); rb_define_method(rb_cMatch, "select", match_select, -1); rb_define_method(rb_cMatch, "pre_match", rb_reg_match_pre, 0); --=-m82svbvaD7u2IgR4djuV--