简体   繁体   中英

Why doesn't slicing with negative position values work as expected in Ruby?

I'm working my way through a Ruby tutorial (just for hoops and giggles) and while experimenting around one of the examples this behavior struck me as unexpected:

s = "hello"
s[1, 2]          # => "el"
s[1 .. 2]        # => "el"
s[-4 .. -3]      # => "el"
s[-4, -3]        # => nil ... but why?

I would have expected the last line to yield the same result as the one before it. After all it works that way with positive slice values. Where am I going wrong?

Because a negative length for the slice doesn't make sense. The slice method takes an index, or a range of indexes, or a start and length.

s[-4 .. -3] # here you're passing the slice method a range of numbers
s[-4, -3]   # here you're passing the slice method: start = -4, length = -3

s[-4, 2] => "el"

Documentation for the slice method for the String class

a[x, y] is " y elements from a , starting from x "

a[x..y] is "elements from x to y from a "

If you try this, you'll see that positive numbers don't match either - you just had a coincidence:

a = [1, 2, 3, 4, 5, 6]
a[3, 2]   # [4, 5] (i.e. two elements from a, starting from the third)
a[3..2]   # []     (i.e. elements from third to second, from a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM