Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the Ruby equivalent of Python's output[:-1]?

Tags:

python

ruby

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?

like image 853
Thierry Lam Avatar asked Mar 20 '10 21:03

Thierry Lam


2 Answers

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.

like image 62
Mark Rushakoff Avatar answered Oct 13 '22 00:10

Mark Rushakoff


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.

like image 31
Mike Graham Avatar answered Oct 13 '22 00:10

Mike Graham