tags:

views:

144

answers:

5

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?

+2  A: 

"stackoverflow"[0..-2] will return "stackoverflo"

hermannloose
+4  A: 

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.

Mike Graham
You can choose whether a range includes its end. Two dots (`0..-2`) includes the last element while the three-dot form (`0...-1`) excludes it.
Chuck
@Chuck, Thanks. I was just editing to say so. :)
Mike Graham
+1  A: 

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!
Pete
Note that `chop` will remove two characters if the string ends in `\r\n`.
Phil Ross
+1  A: 

If you only want to remove the last character, you can also do

output.chop
sepp2k
+9  A: 

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.

Mark Rushakoff
Now, that made me read the docs for Range again and learn about triple dots for the first time. Nice!
hermannloose
My gripe with two-dots vs. three-dots is it's easy to mistake/miscount the number of dots, increasing the chance of a bug or making maintenance a bit more difficult. In my opinion, using three is more of a curiosity as it really doesn't help me write clearer code.
Greg
@Z.E.D.: One of the use cases for 3-dot ranges is running a case statement over floats. See page 97 of the Pickaxe book for Ruby 1.9, if you have it.
Mark Rushakoff