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!

4 Comments:
Um, the #last methods on Array and String already do that in Ruby.
10:41 PM, June 08, 2006
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
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
It's in ruby 1.8.3 aswell!
6:26 AM, October 01, 2006
Post a Comment
<< Home