Getting a substring in Ruby by x number of chars

Posted by wotaskd on Stack Overflow See other posts from Stack Overflow or by wotaskd
Published on 2010-12-24T19:42:37Z Indexed on 2010/12/24 19:54 UTC
Read the original article Hit count: 152

Filed under:

I'm trying to produce some Ruby code that will take a string and return a new one, with a number x number of characters removed from its end - these can be actual letters, numbers, spaces etc.

Ex: given the following string

a_string = "a1wer4zx"

I need a simple way to get the same string, minus - say - the 3 last digits. In the case above, that would be "a1wer". The way I'm doing it right now seems very convoluted:

an_array = a_string.split(//,(a_string.length-2))
an_array.pop
new_string = an_array.join

Any ideas?

© Stack Overflow or respective owner

Related posts about ruby