Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/arrays.rb

Overview

Array extension

Instance Method Summary collapse

Instance Method Details

#check_empty_listObject

throw exception if list is empty



24
25
26
# File 'lib/arrays.rb', line 24

def check_empty_list
  throw ":empty list" if self.empty?
end

#cluster(&block) ⇒ Object

cluster element with keep order accept binary predicate function [1, 2, 2, 2].cluster { |a, b| a == b }

> [[1], [2, 2, 2]]



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/arrays.rb', line 8

def cluster &block
  self.inject([]) { |acc, item|
    if acc.empty?
      [[item]]
    else
      if block.call(acc[-1][-1], item)
        acc[-1] << item
      else
        acc << [item]
      end
      acc
    end
  }
end

#headObject

take one element [1, 2].head

> 1



47
48
49
# File 'lib/arrays.rb', line 47

def head
  self.first
end

#initObject

drop last one element [1, 2].tail

> [2]



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

def init
  check_empty_list
  self.take(self.length-1)
end

#tailObject

drop one element [1, 2].tail

> [2]



39
40
41
42
# File 'lib/arrays.rb', line 39

def tail
  check_empty_list
  self.drop(1)
end