Getting a substring in Ruby by x number of chars
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
Use something like this:
s = "abcdef"
new_s = s[0..-2] # new_s = "abcde"
See the slice
method here: http://ruby-doc.org/core/classes/String.html
Another option could be to use the slice
method
a_string = "a1wer4zx"
a_string.slice(0..5)
=> "a1wer4"
Documentation: http://ruby-doc.org/core-2.5.0/String.html#method-i-slice
Another option is getting the list of chars
of the string, take
ing x chars and join
ing 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