Method: Immutable::Vector#slice

Defined in:
lib/immutable/vector.rb

#vector.slice(index) ⇒ Object #vector.slice(index, length) ⇒ Vector #vector.slice(index..end) ⇒ Vector Also known as: []

Return specific objects from the Vector. All overloads return nil if the starting index is out of range.

Overloads:

  • #vector.slice(index) ⇒ Object

    Returns a single object at the given index. If index is negative, count backwards from the end.

    Examples:

    v = Immutable::Vector["A", "B", "C", "D", "E", "F"]
    v[2]  # => "C"
    v[-1] # => "F"
    v[6]  # => nil
  • #vector.slice(index, length) ⇒ Vector

    Return a subvector starting at index and continuing for length elements or until the end of the Vector, whichever occurs first.

    Examples:

    v = Immutable::Vector["A", "B", "C", "D", "E", "F"]
    v[2, 3]  # => Immutable::Vector["C", "D", "E"]
    v[-2, 3] # => Immutable::Vector["E", "F"]
    v[20, 1] # => nil
  • #vector.slice(index..end) ⇒ Vector

    Return a subvector starting at index and continuing to index end or the end of the Vector, whichever occurs first.

    Examples:

    v = Immutable::Vector["A", "B", "C", "D", "E", "F"]
    v[2..3]    # => Immutable::Vector["C", "D"]
    v[-2..100] # => Immutable::Vector["E", "F"]
    v[20..21]  # => nil


322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/immutable/vector.rb', line 322

def slice(arg, length = (missing_length = true))
  if missing_length
    if arg.is_a?(Range)
      from, to = arg.begin, arg.end
      from += @size if from < 0
      to   += @size if to < 0
      to   += 1     if !arg.exclude_end?
      length = to - from
      length = 0 if length < 0
      subsequence(from, length)
    else
      get(arg)
    end
  else
    arg += @size if arg < 0
    subsequence(arg, length)
  end
end