In Python, if I want to get the first n characters of a string minus the last character, I do:
output = 'stackoverflow'
print output[:-1]
What's the Ruby equivalent?
In Python, if I want to get the first n characters of a string minus the last character, I do:
output = 'stackoverflow'
print output[:-1]
What's the Ruby equivalent?
Your current Ruby doesn't do what you describe: it cuts off the last character, but it also reverses the string.
The closest equivalent to the Python snippet would be
output = 'stackoverflow'
puts output[0...-1]
You originally used ..
instead of ...
(which would work if you did output[0..-2]
); the former being closed–closed the latter being closed–open. Slices—and most everything else—in Python are closed–open.
If all you want to do is remove the last character of the string, you can use the 'chop' method as well:
puts output.chop
or
puts output.chop!
If you only want to remove the last character, you can also do
output.chop
I don't want to get too nitpicky, but if you want to be more like Python's approach, rather than doing "StackOverflow"[0..-2]
you can do "StackOverflow"[0...-1]
for the same result.
In Ruby, a range with 3 dots excludes the right argument, where a range with two dots includes it. So, in the case of string slicing, the three dots is a bit more close to Python's syntax.