[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Re: testing and assigning with regexp's

Tim Hunter

5/2/2007 11:23:00 AM

Mike Steiner wrote:
> I'm new to Ruby, and in a little program I'm writing, I have code like
> this:
>
> str = ''
> if /something/.match(str)
> str = /something/.match(str)[1]
> end
>
> Is there a more elegant way to do this?
>
> Mike Steiner
>
str = ''
m = /something/.match(str)
str = m[1] if m

--
RMagick [http://rmagick.rub...]
RMagick Installation FAQ [http://rmagick.rub.../install-faq.html]


2 Answers

Brian Candler

5/2/2007 11:58:00 AM

0

On Wed, May 02, 2007 at 08:23:13PM +0900, Tim Hunter wrote:
> Mike Steiner wrote:
> >I'm new to Ruby, and in a little program I'm writing, I have code like
> >this:
> >
> >str = ''
> >if /something/.match(str)
> > str = /something/.match(str)[1]
> >end
> >
> >Is there a more elegant way to do this?
> >
> >Mike Steiner
> >
> str = ''
> m = /something/.match(str)
> str = m[1] if m

A useful pattern is:
str = $1 if /(something)/ =~ str

or without the capture:
str = $& if /something/ =~ str

Christian Neukirchen

5/4/2007 1:35:00 PM

0

Tim Hunter <TimHunter@nc.rr.com> writes:

> Mike Steiner wrote:
>> I'm new to Ruby, and in a little program I'm writing, I have code
>> like this:
>>
>> str = ''
>> if /something/.match(str)
>> str = /something/.match(str)[1]
>> end
>>
>> Is there a more elegant way to do this?
>>
>> Mike Steiner
>>
> str = ''
> m = /something/.match(str)
> str = m[1] if m

str = str[/something/, 1] || str

--
Christian Neukirchen <chneukirchen@gmail.com> http://chneuk...