Quantcast

Ruby on Rails, Io, Lisp, JavaScript, Dynamic Languages, Prototype-based programming and more...

Technoblog reader special: $10 off web hosting by FatCow!

Thursday, June 08, 2006

Last n Characters of a Ruby String

Almost without fail people come to me after using Ruby for a while and ask if there is any easy way to get the last n characters of a string. The easiest way to do it without extending classes is:


str = 'This is a test'
srt[-4,4] # => 'test'

However if you are willing to mixin a nice little method you will forevermore have rapid access to the last characters of a string.


module LastN
def last(n)
self[-n,n]
end
end

class String
include LastN
end

'This is a test'.last(4) # => 'test'

Enjoy!

You should follow me on twitter here.

Technoblog reader special: click here to get $10 off web hosting by FatCow!

7 Comments:

Anonymous josh said...

Um, the #last methods on Array and String already do that in Ruby.

10:41 PM, June 08, 2006

 
Blogger choonkeat said...

You mean Array and Range? String doesn't have #last and Range#last has no arguments, its actually Range#end

irb(main):006:0> [1,2,3,4,5].last(2)
=> [4, 5]
irb(main):007:0> "hello".last(2)
NoMethodError: undefined method `last' for "hello":String
from (irb):7
from :0
irb(main):008:0> (0..5).last(2)
ArgumentError: wrong number of arguments (1 for 0)
from (irb):8:in `last'
from (irb):8
from :0
irb(main):009:0> (0..5).last
=> 5

11:21 PM, June 08, 2006

 
Anonymous josh said...

D'oh! I was using the Rails console. ActiveSupport adds the String method for last(n). But Ruby 1.8.4 includes it for Array already.

10:12 AM, June 09, 2006

 
Anonymous Small Business Web Hosting said...

It's in ruby 1.8.3 aswell!

6:26 AM, October 01, 2006

 
Blogger V Jayant said...

You could also directly add the last(n) function to the String class

class String
def last(n)
self[-n,n]
end
end

"This works too".last(3) # => "too"

5:59 AM, April 13, 2010

 
Anonymous Leo said...

The ActiveSupport version also works when the length you want to clip to is greater than the length of the string, e.g.

"short string".last(20) -> "short string"

whereas your function will return nil

10:44 AM, June 06, 2011

 
Anonymous roger said...

yeah this returns nil if you give it too low a number. Which is really ruby's bug but hey...

4:24 AM, January 20, 2012

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home

 

If you like this blog, you might also like top photography schools.