Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best way to remove the last n characters of a string (in Ruby)? [duplicate]

Tags:

ruby

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!

like image 899
Tao Avatar asked Jun 17 '10 07:06

Tao


People also ask

How do you remove the last few characters of a string?

Using String. The easiest way is to use the built-in substring() method of the String class. In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character.

How do I remove the last 3 characters from a string?

slice() method to remove the last 3 characters from a string, e.g. const withoutLast3 = str. slice(0, -3); . The slice method will return a new string that doesn't contain the last 3 characters of the original string.


2 Answers

You can use ranges.

"string"[0..-4]
like image 139
August Lilleaas Avatar answered Oct 20 '22 18:10

August Lilleaas


You could use a regex with gsub ...

"string".gsub( /.{3}$/, '' )
like image 25
irkenInvader Avatar answered Oct 20 '22 18:10

irkenInvader