Class: Array

Inherits:
Object show all
Defined in:
lib/rubyexts/array.rb,
lib/rubyexts/random.rb

Direct Known Subclasses

RubyExts::UniqueArray

Instance Method Summary collapse

Instance Method Details

#onlyObject

Returns the only element in the array or raise IndexError if array hasn’t exactly one element.

Examples:

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

Returns:

  • (Object)

    First (and only) item of the array

Raises:

  • (IndexError)

    If array hasn’t exactly one element

Author:

  • Botanicus

Since:

  • 0.0.3



16
17
18
19
# File 'lib/rubyexts/array.rb', line 16

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

#randObject Also known as: random

Returns random item from the array

Returns:

  • (Object)

    Random item from array

Author:

  • Botanicus

Since:

  • 0.0.2



9
10
11
# File 'lib/rubyexts/random.rb', line 9

def rand
  self[Kernel.rand(length)]
end