16

in Ruby, I just want to get rid of the last n characters of a string, but the following doesn't work

"string"[0,-3]

nor

"string".slice(0, -3)

I'd like a clean method, not anything like

"string".chop.chop.chop

it may be trivial, please anyone teach me! thanks!

Tao
  • 970
  • 1
  • 12
  • 21
  • 7
    +1 for `chop.chop.chop`. Makes me think of you as taking an axe to the end of the string. :-) – Donal Fellows Jun 17 '10 at 07:56
  • 1
    `chop.chop.chop` has the added disadvantage of making three extra copies of your `String`. If it's just `"hello, world"`, then that won't matter, but if it's `File.read('/some/really/big.file')`, it will. – James A. Rosen Jun 17 '10 at 14:12
  • The opposite task, getting the last `n` bytes/characters/whatever from your string is slightly tricky: http://stackoverflow.com/questions/2174767/extracting-the-last-n-characters-from-a-ruby-string – Andrew Grimm Jun 18 '10 at 01:10
  • See also: [Ruby, remove last N characters from a string?](http://stackoverflow.com/q/4209384/1591669) – unor Sep 25 '15 at 01:23

3 Answers3

27

You can use ranges.

"string"[0..-4]
August Lilleaas
  • 54,010
  • 13
  • 102
  • 111
9

You could use a regex with gsub ...

"string".gsub( /.{3}$/, '' )
irkenInvader
  • 1,396
  • 1
  • 11
  • 17
1

If you add an ! to slice it will destructively remove the last n characters without having to assign it to another variable:

my_string.slice!(my_string.length-3,my_string.length)

compared to:

new = my_string.slice(0..-4)
Blake Erickson
  • 755
  • 1
  • 9
  • 28