Reputation: 4743
I want something as simple as the pseudocode below:
ar = [4,5,6,7,8,9]
last = ar.length-1
s = ar[0, 1..3, last] #fake code
puts s
Expected output has no 8: 4,5,6,7,9
Error:
bs/test.rb:12:in `[]': wrong number of arguments (3 for 2) (ArgumentError)
I know that it can accept only two args. Is there a simple way to get what I need ?
Upvotes: 0
Views: 48
Reputation: 108
You can do it this way also -
ar = [4,5,6,7,8,9]
arr = []
arr << ar[0..0] #arr[0] will return a single value but ar[0..0] will return it in array.
arr << ar[1..3]
arr << ar[-1..-1]
on printing arr
it will give following output -
[[4], [5, 6, 7], [9]]
Upvotes: 1
Reputation: 369458
You almost have it, you're just using the wrong method, you should be using Array#values_at
instead of Array#[]
:
ar.values_at(0, 1..3, -1)
# => [4, 5, 6, 7, 9]
Also note that in Ruby, indices "wrap around", so that -1
is always the last element, -2
is second-to-last and so on.
Upvotes: 4