[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Simple question(s

Thomas Adam

9/4/2003 12:55:00 PM

Presumably, one can also use a "try..catch" scenario here too?

-- Thomas Adam

--- Gavin Sinclair <gsinclair@soyabean.com.au> wrote:

> On Thursday, September 4, 2003, 12:04:47 PM, Jason wrote:
>
> > this = "Dec 12"
> > that, other = /(\w+) (\d+)/.match(this).captures
> > p that, other
>
> > ....but this will run into problems when there's not a match, and
> > Regexp#match returns nil. So something like this might be better
>
> > if m = /(\w+) (\d+)/.match(this)
> > that, other = m.captures
> > # Do stuff with "that" and "other"
> > else
> > # We didn't match, do something about it
> > end
>
>
> Good point. I'd probably use exception handling.
>
> that, other = REGEX.match(STR).captures rescue []
>
> The two variables will receive nil if the match fails. That's
> slightly dodgy (may catch other exception?) but concise. If you want
> to handle it more explicitly, then
>
> begin
> that, other = REGEX.match(STR).captures
> rescue NoMethodError
> # handle it
> end
>
> Gavin
>
>

=====
Thomas Adam

"The Linux Weekend Mechanic" -- www.linuxgazette.com

________________________________________________________________________
Want to chat instantly with your online friends? Get the FREE Yahoo!
Messenger http://mail.messenger.y...

1 Answer

Gavin Sinclair

9/4/2003 1:48:00 PM

0

On Thursday, September 4, 2003, 10:55:27 PM, Thomas wrote:

> Presumably, one can also use a "try..catch" scenario here too?

"try" and "catch" mean nothing in Ruby.

Gavin


> --- Gavin Sinclair <gsinclair@soyabean.com.au> wrote:

>> On Thursday, September 4, 2003, 12:04:47 PM, Jason wrote:
>>
>> > this = "Dec 12"
>> > that, other = /(\w+) (\d+)/.match(this).captures
>> > p that, other
>>
>> > ....but this will run into problems when there''s not a match, and
>> > Regexp#match returns nil. So something like this might be better
>>
>> > if m = /(\w+) (\d+)/.match(this)
>> > that, other = m.captures
>> > # Do stuff with "that" and "other"
>> > else
>> > # We didn''t match, do something about it
>> > end
>>
>>
>> Good point. I''d probably use exception handling.
>>
>> that, other = REGEX.match(STR).captures rescue []
>>
>> The two variables will receive nil if the match fails. That''s
>> slightly dodgy (may catch other exception?) but concise. If you want
>> to handle it more explicitly, then
>>
>> begin
>> that, other = REGEX.match(STR).captures
>> rescue NoMethodError
>> # handle it
>> end
>>
>> Gavin
>>
>>

> =====
> Thomas Adam

> "The Linux Weekend Mechanic" -- www.linuxgazette.com