RCR String#{last, first}

Hello.
I noticed today that it is very easy to get the first few characters of
a String:

string[0..whatever]

however, it is harder to get the last few characters of a String

string[-8..-1] || string

Feature request/proposal:
String#last(n)
like

string.last(8)

Feedback welcome.
-roger-

···

--
Posted via http://www.ruby-forum.com/.

If you think you really need it, you can just monkeypatch it in. Then
if you are finding it very useful, you can request it be added to the
class as distributed.

-Dave

···

On Fri, Jan 20, 2012 at 11:47, Roger Pack <rogerpack2005@gmail.com> wrote:

Feature request/proposal:
String#last(n)

--
Dave Aronson, President, Dave Aronson Software Engineering and Training
Ruby on Rails Freelancing (Northern Virginia, Washington DC, or Remote)
DaveAronson.com, Codosaur.us, Dare2XL.com, & RecruitingRants.com (NEW!)
Specialization is for insects. (Heinlein) - Have Pun, Will Babble! (me)

Hello.
I noticed today that it is very easy to get the first few characters of
a String:

string[0..whatever]

however, it is harder to get the last few characters of a String

string[-8..-1] || string

Feature request/proposal:
String#last(n)
like

string.last(8)

Feedback welcome.
-roger-

--
Posted via http://www.ruby-forum.com/\.

There's always the two argument form of slice:

"my string"[-3, 3]

# => "ing"

Not quite as nice as yours, however.

pete

···

On Fri, Jan 20, 2012 at 8:47 AM, Roger Pack <rogerpack2005@gmail.com> wrote:

You should add this request to the bug tracker to ruby.

I don't think matz and many others regularly read every mail here. :slight_smile:

I do agree with you - I think .last(5) would be nice and more readable
than "foobar"[-5,5] # => "oobar"

"foobar"[-5,5] # => "oobar"

"foobar".last 5 # => "oobar"

But I also must say, I am now so used to use [] that I don't use
anything else. For the record, I also don't use .slice

I just love [] too much.

···

--
Posted via http://www.ruby-forum.com/.

+1

I think these are good methods too. They are defined in Ruby Facets, but in
a bit different way then one would expect.

http://rubyworks.github.com/rubyfaux/?doc=http://rubyworks.github.com/facets/docs/facets-2.9.3/core.json#api-module-Indexable

I'd like to go whole hog here and propose Ruby adopt the Indexable module.

however, it is harder to get the last few characters of a String

string[-8..-1] || string

You could try something like this.

str = "123456789"
p str[/.{1,8}\z/]

p str[/\A.{1,8}/]

Harry

string[-8..-1] || string

...

There's always the two argument form of slice:

"my string"[-3, 3]

# => "ing"

And it still has this "feature":

>> "123"[-5,5]
=> nil

···

On 01/20/2012 02:52 PM, Pete Higgins wrote:

On Fri, Jan 20, 2012 at 8:47 AM, Roger Pack<rogerpack2005@gmail.com> wrote: