From: dblack@... Date: 2002-08-29T05:48:52+09:00 Subject: Re: Newbie converting brain from perl Hello -- On Thu, 29 Aug 2002, 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? Well, my response to this problem was to participate in a coding retreat where we implemented scanf :-) (See earlier thread on this.) require 'scanf' d = "28 August 2002" day,month,year = d.scanf("%d%s%d") p day, month, year => 28 "August" 2002 (You can get scanf at .) You could also do: day,month,year = d.scan(/(\d+) (\w+) (\d+)/).flatten You need to flatten the scan results because scan returns an array of ()-captured substrings for every successful scan through the array -- so otherwise, day will be a three-element array and month and year will be nil. (Note that scanf gives you the %d fields as numbers (in case that's a consideration), whereas match and scan give you strings.) David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav