Getting a Substring in Ruby by X Number of Chars

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 characters. 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?

1

5 Answers

How about this?

s[0, s.length - 3]

Or this

s[0..-4]

edit

s = "abcdefghi"
puts s[0, s.length - 3]  # => abcdef
puts s[0..-4]            # => abcdef
2

Use something like this:

s = "abcdef"
new_s = s[0..-2] # new_s = "abcde"

See the slice method here:

0

Another option could be to use the slice method

a_string = "a1wer4zx"
a_string.slice(0..5) 
=> "a1wer4"   

Documentation:

Another option is getting the list of chars of the string, takeing x chars and joining back to a string:

[13] pry(main)> 'abcdef'.chars.take(2).join
=> "ab"
[14] pry(main)> 'abcdef'.chars.take(20).join
=> "abcdef"

if you need it in rails you can use first (source code)

s = '1234567890'
x = 4
s.first(s.length - x) # => "123456"

there is also last (source code)

s.last(2) # => "90"

alternatively check from/to

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest