tags:

views:

63

answers:

2

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!

+5  A: 

You can use ranges.

"string"[0..-4]
August Lilleaas
You beat me to it! You can also do this with slice: "string".slice(0..-4)
sosborn
[ ] and slice are synonums
Tao
hi, thanks! I just found that I made a mistake on the second parameter of [ ] or slice; it is length rather than the ending position...
Tao
Careful! In Ruby 1.8, this *does not* remove the last characters, it removes the last *bytes*!
Jörg W Mittag
Or `"string"[0...-3]`
Marc-André Lafortune
+1  A: 

You could use a regex with gsub ...

"string".gsub( /.{3}$/, '' )
irkenInvader