I want to pull two values out from an array based on their index.
Unfortunately this fails when the last index is zero and I don't undertand why.
my_array = ["a", "b", "c", "d", "e", "f", "g"]
my_array[1,2]
# => ["b", "c"]
my_array[0,2]
# => ["a", "b"]
my_array[2,0]
# => []
Why does the last allocation fail to pull out elements 2 and 0?
I suspect my operation is not in fact doing what I think at all since adding a third index makes the whole thing fail:
my_array[1,2,3]
# => Argu开发者_运维百科mentError: wrong number of arguments (3 for 1..2)
What am I actually doing with the array[var1, var2] syntax and what should I be doing?
my_array[start,length]
[docs] is the slice syntax:
returns a subarray starting at start and continuing for length elements
This is a short syntax for my_array.slice(start, length);
You should do this instead:
my_array.values_at(2, 0)
=> ["c", "a"]
See Array#values_at
and Array#slice
精彩评论