Class Array
In: lib/extensions/array.rb
Parent: Object

Methods

only   rand   select!  

Public Instance methods

Returns the only element in the array. Raises an IndexError if the array’s size is not 1.

  [5].only      # -> 5
  [1,2,3].only  # -> IndexError
  [].only       # -> IndexError

[Source]

# File lib/extensions/array.rb, line 39
    def only
      unless size == 1
        raise IndexError, "Array#only called on non-single-element array"
      end
      first
    end

Return a randomly-chosen (using Kernel.rand) element from the array.

  arr = [48, 71, 3, 39, 15]
  arr.rand     # -> 71
  arr.rand     # -> 39
  arr.rand     # -> 48
  # etc.

[Source]

# File lib/extensions/array.rb, line 62
    def rand
      idx = Kernel.rand(size)
      at(idx)
    end

In-place version of Array#select. (Counterpart to, and opposite of, the built-in reject!)

[Source]

# File lib/extensions/array.rb, line 19
    def select!
      reject! { |e| not yield(e) }
    end

[Validate]