Array.[] and Array.slice
Signature
array[position] #=> object or nil
array.slice(position) #=> object or nil
array[position] and array.slice(position) returns the object atposition or returns nil if position is outside of array. If position
is 0 or positive, then start counting from the beginning of the array. Ifposition is negative, then start counting from the end of the array.
array[position, count] #=> new_array or nil
array.slice(position, count) #=> new_array or nil
array[position,count] and array.slice(position,count) returnsnew_array containing count number of objects starting from position.count must be a positive integer or nil is returned. If count is 0 then
an empty array is returned (and not to mention executing useless method call).
If position is positive and outside of array then an empty array is
returned. If position is 0 or positive, then start counting from the
beginning of the array. If position is negative, then start counting from
the end of the array. If position is negative and outside of array thennil is returned.
array[range] #=> new_array or nil
array.slice(range) #=> new_array or nil
array[range] and array.slice(range) returns new_array containing each
object for all positions specified by range. If the start of the range is 0
or positive then start counting from the beginning of the array. If the start
of the range is negative then start counting from the end of the array. If the
start of the range is negative and outside of array then nil is
returned.
Examples
a = [1, 2, "foo", 3, "bar", 4, -9]
a[0] #=> 1
a[1] #=> 2
a[-1] #=> -9
a[20] #=> nil
a[-20] #=> nil
a[2,3] #=> ["foo", 3, "bar"]
a[2,-3] #=> nil
a[7,2] #=> []
a[1,0] #=> []
a[-2,3] #=> [4, -9]
a[-3,3] #=> ["bar", 4, -9]
a[-8,2] #=> nil
a[99, 5] #=> nil
a[-99, 5] #=> nil
a[0..99] #=> [1, 2, "foo", 3, "bar", 4, -9]
a[2..5] #=> ["foo", 3, "bar", 4]
a[2..-4] #=> ["foo", 3]
a[2..-99] #=> []
a[7..10] #=> []
a[0..0] #=> [1]
a[-5..-2] #=> ["foo", 3, "bar", 4]
a[-5..-1] #=> ["foo", 3, "bar", 4, -9]
a[-5..-6] #=> []
a[-99..-1] #=> nil
a[-99..0] #=> nil
a[-99..1] #=> nil
a.slice(0) #=> 1
a.slice(1) #=> 2
a.slice(-1) #=> -9
a.slice(20) #=> nil
a.slice(-20) #=> nil
a.slice(2,3) #=> ["foo", 3, "bar"]
a.slice(2,-3) #=> nil
a.slice(7,2) #=> []
a.slice(1,0) #=> []
a.slice(-2,3) #=> [4, -9]
a.slice(-3,3) #=> ["bar", 4, -9]
a.slice(-8,2) #=> nil
a.slice(99, 5) #=> nil
a.slice(-99, 5) #=> nil
a.slice(0..99) #=> [1, 2, "foo", 3, "bar", 4, -9]
a.slice(2..5) #=> ["foo", 3, "bar", 4]
a.slice(2..-4) #=> ["foo", 3]
a.slice(2..-99) #=> []
a.slice(7..10) #=> []
a.slice(0..0) #=> [1]
a.slice(-5..-2) #=> ["foo", 3, "bar", 4]
a.slice(-5..-1) #=> ["foo", 3, "bar", 4, -9]
a.slice(-5..-6) #=> []
a.slice(-99..-1) #=> nil
a.slice(-99..0) #=> nil
a.slice(-99..1) #=> nil
Documentation Reference
Ruby version 1.8.6
- Log in to post comments
