[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Re: substring: to the end of the string

Austin Ziegler

11/15/2003 2:59:00 PM

On Sat, 15 Nov 2003 10:24:42 +0900, Bermejo, Rodrigo wrote:
> class String
> def substring
> /(^...)(.*)\z/ =~ self
> return $2
> end
> end

As Gavin pointed out, regexen are overkill here. However, the
technique is worth noting:

class String
def substring(start, len = nil)
if len.nil?
/^.{#{start}}(.*)/m =~ self
else
/^.{#{start}}(.{#{len}})/m =~ self
end
$1
end
end

"123456".substring(3) # => "456"
"123456".substring(3, 2) # => "45"

-austin
--
austin ziegler * austin@halostatue.ca * Toronto, ON, Canada
software designer * pragmatic programmer * 2003.11.15
* 09.51.26




1 Answer

nobu.nokada

11/17/2003 3:40:00 AM

0

Hi,

At Sat, 15 Nov 2003 23:58:55 +0900,
Austin Ziegler wrote:
> As Gavin pointed out, regexen are overkill here. However, the
> technique is worth noting:

Another syntax sugar,

> class String
> def substring(start, len = nil)
> if len.nil?
self[/\A.{#{start}}(.*)/m, 1]
> else
self[/\A.{#{start}}(.{#{len}})/m, 1]
> end
> $1
> end
> end

--
Nobu Nakada