[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    Re: Chopping the beginning of a string elegantly
From:       Wybo Dekker <wybo () servalys ! nl>
Date:       2005-07-29 13:28:30
Message-ID: 42EA2EEF.7010005 () servalys ! nl
[Download RAW message or body]

Wybo Dekker wrote:

> francisrammeloo@hotmail.com wrote:
>
>> Hi all,
>>
>> I'm having some trouble finding an elegant way of removing a part of a
>> string based on an pattern.
>>
>> Suppose I want to chop off the "Begin" in the string "BeginCaption".
>>  
>>
> irb(main):001:0>  w='BeginCaption'
> => "BeginCaption"
> irb(main):002:0> w.slice!(/^Begin/)
> => "Begin"
> irb(main):003:0> w
> => "Caption"
>
but what you asked was perhaps more like this:
irb(main):004:0>  widgetdescription='BeginCaption'
=> "BeginCaption"
irb(main):005:0> (thePane=widgetdescription).slice!(/^Begin/)
=> "Begin"
irb(main):006:0> thePane
=> "Caption"

if there is no match:
irb(main):007:0> widgetdescription='EndCaption'
=> "EndCaption"
irb(main):008:0> (thePane=widgetdescription).slice!(/^Begin/) or warn 
"no match"
no match
=> nil
irb(main):009:0> thePane
=> "EndCaption"

or perhaps:
irb(main):010:0> thePane=/^Begin(.*)/.match(widgetdescription)[1]
=> "Caption"
(but that goes wrong if there is no ^Begin)


-- 

Wybo

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic