Method: Immutable::SortedSet#fetch

Defined in:
lib/immutable/sorted_set.rb

#fetch(index) ⇒ Object #fetch(index) {|index| ... } ⇒ Object #fetch(index, default) ⇒ Object

Retrieve the value at index with optional default.

Overloads:

  • #fetch(index) ⇒ Object

    Retrieve the value at the given index, or raise an IndexError if not found.

    Examples:

    s = Immutable::SortedSet["A", "B", "C", "D"]
    s.fetch(2)       # => "C"
    s.fetch(-1)      # => "D"
    s.fetch(4)       # => IndexError: index 4 outside of vector bounds

    Parameters:

    • index (Integer)

      The index to look up

    Raises:

    • (IndexError)

      if index does not exist

  • #fetch(index) {|index| ... } ⇒ Object

    Retrieve the value at the given index, or return the result of yielding the block if not found.

    Examples:

    s = Immutable::SortedSet["A", "B", "C", "D"]
    s.fetch(2) { |i| i * i }   # => "C"
    s.fetch(4) { |i| i * i }   # => 16

    Parameters:

    • index (Integer)

      The index to look up

    Yields:

    • Once if the index is not found.

    Yield Parameters:

    • index (Integer)

      The index which does not exist

    Yield Returns:

    • (Object)

      Default value to return

  • #fetch(index, default) ⇒ Object

    Retrieve the value at the given index, or return the provided default value if not found.

    Examples:

    s = Immutable::SortedSet["A", "B", "C", "D"]
    s.fetch(2, "Z")  # => "C"
    s.fetch(4, "Z")  # => "Z"

    Parameters:

    • index (Integer)

      The index to look up

    • default (Object)

      Object to return if the key is not found

Returns:

  • (Object)


254
255
256
257
258
259
260
261
262
263
264
# File 'lib/immutable/sorted_set.rb', line 254

def fetch(index, default = (missing_default = true))
  if index >= -@node.size && index < @node.size
    at(index)
  elsif block_given?
    yield(index)
  elsif !missing_default
    default
  else
    raise IndexError, "index #{index} outside of sorted set bounds"
  end
end