Class: NonEmptyArray

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Includes:
Enumerable
Defined in:
lib/non_empty_array.rb

Overview

An enumerable which is guaranteed to not be empty.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(first_element, tail = []) ⇒ NonEmptyArray

Returns a new instance of NonEmptyArray.



14
15
16
17
# File 'lib/non_empty_array.rb', line 14

def initialize(first_element, tail = [])
  @head = first_element
  @tail = tail
end

Instance Attribute Details

#tailObject (readonly)

Returns the value of attribute tail.



37
38
39
# File 'lib/non_empty_array.rb', line 37

def tail
  @tail
end

Instance Method Details

#all_but_lastObject



32
33
34
# File 'lib/non_empty_array.rb', line 32

def all_but_last
  T.must(all_elements.slice(0..-2))
end

#each(&block) ⇒ Object



20
21
22
# File 'lib/non_empty_array.rb', line 20

def each(&block)
  all_elements.each(&block)
end

#lastObject



25
26
27
28
29
# File 'lib/non_empty_array.rb', line 25

def last
  return @head if @tail.empty?

  @tail[-1]
end

#push(element) ⇒ Object



40
41
42
43
# File 'lib/non_empty_array.rb', line 40

def push(element)
  @tail.push(element)
  self
end