# Getting the last N bytes of a string:

**URL:** <https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691>\
**Category:** Ruby\
**Created:** [June 1, 2007, 1:17pm UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691 "2007-06-01T13:17:46Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 1, 2007, 1:17pm UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/1 "2007-06-01T13:17:46Z")

</div>

What’s the simplest way to get only the last 10 bytes of a string?

```
buf[-10,10]

```

doesn’t work if buf is smaller than 10 bytes, as it returns nil. Is  
there  
anything simpler than

```
buf[-10,10] || buf

```

?

Thanks,

Brian.

P.S. To get the _first_ 10 bytes of a string is easy: buf[0,10] always  
works, whether or not buf is smaller than 10 bytes)

---

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 1, 2007, 2:03pm UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/2 "2007-06-01T14:03:54Z")

</div>

buf.reverse[0,10]?

---

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 1, 2007, 2:06pm UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/3 "2007-06-01T14:06:54Z")

</div>

On 6/1/07, Brian C. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Thanks,
> 
> Brian.
> 
> P.S. To get the _first_ 10 bytes of a string is easy: buf[0,10] always  
> works, whether or not buf is smaller than 10 bytes)

I don’t know if this is simple but you can try something like this.

str =~ /(.{1,10}$)/

Harry

–

A Look into Japanese Ruby List in English  
[http://www.kakueki.com/](http://www.kakueki.com/)

---

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 1, 2007, 3:12pm UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/4 "2007-06-01T15:12:01Z")

</div>

On 6/1/07, Harry K. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> str =~ /(.{1,10}$)/

This works nicely if you do this:  
str[/(.{1,10}$)/]

Though I guess it depends on what you consider “simple”.

---

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 1, 2007, 2:42pm UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/5 "2007-06-01T14:42:50Z")

</div>

Brian C. wrote:

> What’s the simplest way to get only the last 10 bytes of a string?

There are several ways. One option is to pad the string with spaces,  
extract your slice, then strip the leading and trailing whitespace:

buf = “abcdef”

buf.rjust(10, ’ ')[-10, 10].strip

=\> “abcdef”

David

> **[Ruby on Windows](http://rubyonwindows.blogspot.com)**
>
> On using the Ruby programming language on the Microsoft Windows platform

---

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 1, 2007, 3:12pm UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/6 "2007-06-01T15:12:33Z")

</div>

Brian C. wrote:

> What’s the simplest way to get only the last 10 bytes of a string?

Ok. Here is my first attempt at answering a coding question. /deep  
breath

‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’.reverse.slice(0…9).reverse

---

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 1, 2007, 6:22pm UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/7 "2007-06-01T18:22:36Z")

</div>

On 6/2/07, Bertram S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> is what the OP meant.

That is a great answer too 🙂  
I guess the OP didn’t mention newlines, so \z works better.

---

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 1, 2007, 11:51pm UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/8 "2007-06-01T23:51:23Z")

</div>

Brian C. wrote:

> What’s the simplest way to get only the last 10 bytes of a string?
> 
> ```
> buf[-10,10]
> 
> ```
> 
> doesn’t work if buf is smaller than 10 bytes, as it returns nil. Is there  
> anything simpler than
> 
> ```
> buf[-10,10] || buf
> 
> ```

I’d use:

buf[-10…-1] || buf

but this is only a variation of what you have.

There is buf.reverse[0…9].reverse as well, but this looks even uglier  
to me than the first.

Stefan

---

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 1, 2007, 5:41pm UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/9 "2007-06-01T17:41:33Z")

</div>

Hi,

Am Freitag, 01. Jun 2007, 22:10:51 +0900 schrieb Leonard C.:

> On 6/1/07, Harry K. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:
> 
> > str =~ /(.{1,10}$)/
> 
> This works nicely if you do this:  
> str[/(.{1,10}$)/]

str[/(.{1,10}\z)/]

is what the OP meant.

Bertram

---

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 2, 2007, 4:20am UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/10 "2007-06-02T04:20:43Z")

</div>

On 6/1/07, Leonard C. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> On 6/1/07, Harry K. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:
> 
> > str =~ /(.{1,10}$)/
> 
> This works nicely if you do this:  
> str[/(.{1,10}$)/]
> 
> Though I guess it depends on what you consider “simple”.

Well, I guess the parentheses are not necessary.  
This looks a little less cluttered.

str[/.{1,10}$/]

Harry

–

A Look into Japanese Ruby List in English  
[http://www.kakueki.com/](http://www.kakueki.com/)

---

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 2, 2007, 8:22am UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/11 "2007-06-02T08:22:59Z")

</div>

Thanks everyone for your answers.

I think I’ll stick with buf[-10,10] || buf. I was just wondering if I’d  
missed something obvious like buf.last(10), after staring at ‘ri String’  
too  
long.

Finally I found a usage case where perl has the edge 🙂

$ perl -e ‘$a=“abc”;print substr($a,-10),"\n"’  
abc  
$ perl -e ‘$a=“abcdefghijklmnop”;print substr($a,-10),"\n"’  
ghijklmnop

Regards,

Brian.

---

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 2, 2007, 5:59am UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/12 "2007-06-02T05:59:49Z")

</div>

Hi,

Am Freitag, 01. Jun 2007, 20:15:54 +0900 schrieb Brian C.:

> What’s the simplest way to get only the last 10 bytes of a string?
> 
> ```
> buf[-10,10]
> 
> ```
> 
> doesn’t work if buf is smaller than 10 bytes, as it returns nil. Is there  
> anything simpler than
> 
> ```
> buf[-10,10] || buf
> 
> ```
> 
> ?

,From time to time I find myself trying to do something like  
that. Maybe the best thing was if the String#slice method  
were defined for using negative lengths but that’s probably  
too late.

For my personal use I wrote a litte extension doing exactly  
that. You can have it if you want.

[http://www.bertram-scharpf.de/tmp/bs-ruby.tar.gz](http://www.bertram-scharpf.de/tmp/bs-ruby.tar.gz)

Inspite of its shortness it’s surely buggy. Parameter  
definition will ever be a matter of taste. Don’t try to  
convince the core developpers there’s a neccessity to proffer  
a solution for this. No chance.

Bertram

---

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 2, 2007, 4:07pm UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/13 "2007-06-02T16:07:39Z")

</div>

ok, I have a question now. In the original post, he wanted to cover  
errors caused by undersized strings. I have been trying to grok the  
“zen of ruby” from posts in here and I thought that writing Ruby-ish  
code involves two things: 1. making it so that it reads as plain  
English and 2. Letting Ruby do the work for you.

I could do it easily enough in Pascal, for example:

s := @s[length(s) - 10];

but then we need to check for length errors as mentioned before.

Here comes the question, why was my approach wrong? I am assuming that  
it was horrible because no one even bothered to tell me that I was being  
a total goober by saying this:

‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’.reverse.slice(0…9).reverse

I know that just having working code is not enough or we could use C#  
and have done with it. How do we make it readable? How do we let Ruby  
do the work?

It seems to me that approaches like str[/(.{1,10}\z)/] are neither plain  
language readable nor letting Ruby do the work as it seems that the work  
is in the coding.

Assuming that all the variations work equally well, how does one choose  
which is the more “ruby like” in its approach? How can I tell which  
approach is ugly and which is elegant?

---

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 4, 2007, 7:41pm UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/14 "2007-06-04T19:41:19Z")

</div>

On Jun 1, 2007, at 23:14 , Brian C. wrote:

> I think I’ll stick with buf[-10,10] || buf. I was just wondering if  
> I’d  
> missed something obvious like buf.last(10), after staring at ‘ri  
> String’ too  
> long.

you could do that too:

> > “blah blah blah”.split(//).last(4).join  
> > =\> “blah”

or do what you were looking for:

> > class String; def last(n=1); self[-n, n] || self; end; end  
> > =\> nil
> 
> > “blah”.last(10)  
> > =\> “blah”
> 
> > “blah blah”.last(4)  
> > =\> “blah”

---

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 2, 2007, 5:29pm UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/15 "2007-06-02T17:29:05Z")

</div>

On Jun 2, 2007, at 10:07 AM, Lloyd L. wrote:

> but then we need to check for length errors as mentioned before.  
> and have done with it. How do we make it readable? How do we let  
> choose  
> which is the more “ruby like” in its approach? How can I tell which  
> approach is ugly and which is elegant?
> 
> –  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

Well, this is how Rails solves this in ActiveSupport

vendor/rails/activesupport/lib/active\_support/core\_ext/string/access.rb

module ActiveSupport #:nodoc:  
module CoreExtensions #:nodoc:  
module String #:nodoc:  
# Makes it easier to access parts of a string, such as  
specific characters and substrings.  
module Access  
#snip…  
# Returns the last character of the string or the last +limit

- characters.  
#  
# Examples:  
# “hello”.last # =\> “o”  
# “hello”.last(2) # =\> “lo”  
# “hello”.last(10) # =\> “hello”  
def last(limit = 1)  
(chars[(-limit)…-1] || self).to\_s  
end  
end  
end  
end  
end

Which is mixed into String by:  
vendor/rails/activesupport/lib/active\_support/core\_ext/string.rb

require File.dirname( **FILE** ) + ‘/string/inflections’  
require File.dirname( **FILE** ) + ‘/string/conversions’  
require File.dirname( **FILE** ) + ‘/string/access’  
require File.dirname( **FILE** ) + ‘/string/starts\_ends\_with’  
require File.dirname( **FILE** ) + ‘/string/iterators’  
require File.dirname( **FILE** ) + ‘/string/unicode’

class String #:nodoc:  
include ActiveSupport::CoreExtensions::String::Access  
include ActiveSupport::CoreExtensions::String::Conversions  
include ActiveSupport::CoreExtensions::String::Inflections  
include ActiveSupport::CoreExtensions::String::StartsEndsWith  
include ActiveSupport::CoreExtensions::String::Iterators  
include ActiveSupport::CoreExtensions::String::Unicode  
end

So I’d venture to say that the Ruby Way is to simply open up the  
String class and give it a new method. Since there is already an  
Array#first that gives [1,2,3,4].first(2) =\> [1,2], it just seems  
right to match that with .last and move the pair onto String treating  
the individual characters like the elements of the Array.

Although the longer-term would seem to be to reconcile the []  
behavior with Ranges:

> > “abcde”[0…3]  
> > =\> “abc”  
> > “abcde”[-3…-1]  
> > =\> “cde”  
> > “abcdefghijklmno”[-10…-1]  
> > =\> “fghijklmno”  
> > “abcdefghijklmno”[0…10]  
> > =\> “abcdefghij”  
> > “abcd”[0…10]  
> > =\> “abcd”

> > “abcd”[-10…-1]  
> > =\> nil

If only that were also “abcd”.

-Rob

Rob B. [http://agileconsultingllc.com](http://agileconsultingllc.com)  
removed\_email\_address@domain.invalid

---

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 12, 2007, 4:50pm UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/16 "2007-06-12T16:50:37Z")

</div>

What would be the chances of getting something added to the core? It  
seems to me that a new kind of slice would be in order. I know that  
there are lTrim() and rTrim() (left and right) in other languages. What  
about l\_Slice and r\_Slice? Then, it would be:

p ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’.r\_slice(0…9)

---

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 12, 2007, 7:36pm UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/17 "2007-06-12T19:36:43Z")

</div>

Hi,

Am Dienstag, 12. Jun 2007, 23:50:36 +0900 schrieb Lloyd L.:

> What would be the chances of getting something added to the core?

This is what I would have liked to propose.

If anyone understood the `notempty?’ proposal.

Bertram

---

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 12, 2007, 11:16am UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/18 "2007-06-12T11:16:19Z")

</div>

On 2007-06-04 10:40:32 -0700, Ryan D. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
said:

> =\> “blah”
> 
> or do what you were looking for:
> 
> > > class String; def last(n=1); self[-n, n] || self; end; end  
> > > =\> nil  
> > > “blah”.last(10)  
> > > =\> “blah”  
> > > “blah blah”.last(4)  
> > > =\> “blah”

“blah blah blah”.to\_a.last(4).join as well.

It seems like a lot of Array methods would be better served as  
equivalents from Enumerable. #last is one of these.

(It won’t nearly be as fast as a pure Array implementation, but it  
would be extremely useful.)

---

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 12, 2007, 9:59pm UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/19 "2007-06-12T21:59:38Z")

</div>

> p ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’.r\_slice(0…9)

What about this:

def last\_bytes(s, number\_of\_bytes)  
if s.size \> number\_of\_bytes then  
return s.slice(s.size - number\_of\_bytes…s.size)  
end  
return s  
end

p last\_bytes(‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’, 10)  
p last\_bytes(‘WXYZ’, 10)

this is the result:

“QRSTUVWXYZ”  
“WXYZ”

---

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [June 13, 2007, 4:22pm UTC](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691/20 "2007-06-13T16:22:20Z")

</div>

On 13-Jun-07, at 10:15 AM, bbiker wrote:

> irb(main):001:0\> str = “now is the”  
> =\> “now is the”  
> irb(main):002:0\> str[-10…-1]  
> =\> “now is the”
> 
> So I really see no need for a special method to obtain the last x  
> bytes of a string.

str[-100…-1]  
=\> nil

Cheers,  
Bob

* * *

Bob H. – tumblelog at \<http://  
www.recursive.ca/so/\>  
Recursive Design Inc. – weblog at \<[http://www.recursive.ca/](http://www.recursive.ca/)  
hutch\>  
– works at [http://www.recursive.ca/](http://www.recursive.ca/)

[Next page](https://www.ruby-forum.com/t/getting-the-last-n-bytes-of-a-string/105691.md?page=2)
