Module: Enumerable

Defined in:
lib/funkr/extensions/enumerable.rb

Instance Method Summary collapse

Instance Method Details

#all_different?Boolean

Check if all elements in collection are differents

Returns:

  • (Boolean)


12
13
14
15
16
17
18
19
# File 'lib/funkr/extensions/enumerable.rb', line 12

def all_different?
  a = self.to_a.drop(1)
  self.each do |e|
    return false if a.include?(e)
    a.shift
  end
  return true
end

#diff_with(other, &block) ⇒ Object

compare 2 enumerables, and returns [ [missing] , [intersection], [added] ]



73
74
75
76
77
78
79
80
81
82
83
# File 'lib/funkr/extensions/enumerable.rb', line 73

def diff_with(other, &block)
  m, i, a = [], [], []
  u_s = self.make_uniq_by(&block)
  u_o = other.make_uniq_by(&block)
  u_s.each do |e| 
    if u_o.find{|x| yield(e,x)} then i.push(e)  # intersection
    else m.push(e) end   # missing
  end
  u_o.each { |e| a.push(e) unless u_s.find{|x| yield(e,x)} } # added
  return [ m, i, a ]
end

#fold_with(sym) ⇒ Object

Folds an enumerable with an operator



7
8
9
# File 'lib/funkr/extensions/enumerable.rb', line 7

def fold_with(sym)
  self.inject{|a,e| a.public_send(sym,e)}
end

#group_seq_by(&block) ⇒ Object



22
23
24
25
26
27
28
29
30
31
# File 'lib/funkr/extensions/enumerable.rb', line 22

def group_seq_by(&block)
  res = []
  rst = self.to_a
  while !rst.empty? do
    v = yield(rst.first)
    a,rst = rst.span{|x| (yield x) == v}
    res.push(a)
  end
  return res
end

#groups_of(n) ⇒ Object

builds up disjoint groups of n elements or less



44
45
46
47
48
# File 'lib/funkr/extensions/enumerable.rb', line 44

def groups_of(n)
  g = self.take(n)
  return [] if g.empty?
  [g] + self.drop(n).groups_of(n)
end

#make_uniq_by(&block) ⇒ Object

Takes a block predicate p(x,y) and builds an array of elements so that for any (a,b), a being before b in the list, p(a,b) holds.



64
65
66
67
68
69
70
# File 'lib/funkr/extensions/enumerable.rb', line 64

def make_uniq_by(&block)
  result = []
  self.each do |e|
    unless result.any?{|x| yield(x,e)} then result.push(e) end
  end
  return result
end

#seq_index(seq) ⇒ Object

find the position of a sequence

[1,2,3,4,5,4,3,2,1].seq_index([4,3])  # => 5


58
59
60
# File 'lib/funkr/extensions/enumerable.rb', line 58

def seq_index(seq)
  self.sliding_groups_of(seq.size).index(seq)
end

#sliding_groups_of(n) ⇒ Object

builds up sliding groups of exactly n elements



51
52
53
54
# File 'lib/funkr/extensions/enumerable.rb', line 51

def sliding_groups_of(n)
  return [] if self.size < n
  [ self.take(n) ] + self.drop(1).sliding_groups_of(n)
end

#span(&block) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/funkr/extensions/enumerable.rb', line 34

def span(&block)
  inc = []
  self.each_with_index do |e,i|
    if yield(e) then inc.push(e)
    else return [ inc, self.drop(i) ] end
  end
  return [ inc, [] ]
end