Sha256: f1fd997eca55b637c8ab5c4a303c3b5fc1bf13f20924f6de6436ab917d30d183

Contents?: true

Size: 442 Bytes

Versions: 7

Compression:

Stored size: 442 Bytes

Contents

class Array

  # Returns the _only_ element in the array.  Raises an IndexError if
  # the array's size is not 1.
  #
  #   [5].only      # => 5
  #
  #   expect IndexError do
  #     [1,2,3].only
  #   end
  #
  #   expect IndexError do
  #     [].only
  #   end
  #
  # CREDIT: Gavin Sinclair, Noah Gibbs

  def only
    unless size == 1
      raise IndexError, "Array#only called on non-single-element array"
    end
    first
  end

end

Version data entries

7 entries across 6 versions & 1 rubygems

Version Path
facets-2.9.3 lib/core/facets/array/only.rb
facets-2.9.2 src/core/facets/array/only.rb
facets-2.9.2 lib/core/facets/array/only.rb
facets-2.9.1 lib/core/facets/array/only.rb
facets-2.9.0 lib/core/facets/array/only.rb
facets-2.9.0.pre.2 lib/core/facets/array/only.rb
facets-2.9.0.pre.1 lib/core/facets/array/only.rb