Module: DaHuang::ArrayExt

Defined in:
lib/array_ext.rb

Instance Method Summary collapse

Instance Method Details

#include_where(&block) ⇒ Object



19
20
21
22
23
24
# File 'lib/array_ext.rb', line 19

def include_where &block
  self.each do |t|
    return true if block.call(t)
  end
  false
end

#map_hashObject



3
4
5
# File 'lib/array_ext.rb', line 3

def map_hash
  map { |e| yield e }.inject({}) { |carry, e| carry.merge! e }
end

#map_n(&block) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/array_ext.rb', line 87

def map_n(&block)
  return [] unless size>0
  first_row = block.call(self[0])
  rows = self.class.new(first_row.size, [])
  first_row.each_with_index do |val, i|
    rows[i] << val
  end
  self[1..self.size-1].each do |t|
    next_row = block.call(t)
    next_row.each_with_index do |val, i|
      rows[i] << val
    end
  end
  rows
end

#map_to(attrib) ⇒ Object



50
51
52
# File 'lib/array_ext.rb', line 50

def map_to(attrib)
  map{|t| t.try(:send, attrib)}
end

#map_with_indexObject



42
43
44
45
46
47
48
# File 'lib/array_ext.rb', line 42

def map_with_index
  result = []
  self.each_with_index do |elt, idx|
    result << yield(elt, idx)
  end
  result
end

#maps(str) ⇒ Object



7
8
9
10
11
12
13
# File 'lib/array_ext.rb', line 7

def maps(str)
  map{|t|
    str.gsub(/(::)\{([\w_]+?)\}/){|m|
      t.send($2)
    }
  }
end

#minus(*obj) ⇒ Object



54
55
56
# File 'lib/array_ext.rb', line 54

def minus(*obj)
  reject{|t| obj.include? t}
end

#minus!(*obj) ⇒ Object



62
63
64
65
66
# File 'lib/array_ext.rb', line 62

def minus!(*obj)
  each do |t|
    delete(t) if obj.include? t
  end
end

#only(*obj) ⇒ Object



58
59
60
# File 'lib/array_ext.rb', line 58

def only(*obj)
  select{|t| obj.include? t}
end

#only!(*obj) ⇒ Object



68
69
70
71
72
# File 'lib/array_ext.rb', line 68

def only!(*obj)
  each do |t|
    delete(t) unless obj.include? t
  end
end

#search(str) ⇒ Object



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

def search(str)
  map(&:to_s).select{|t| t.include?(str)}
end

#squash(width) ⇒ Object



78
79
80
81
82
83
84
85
# File 'lib/array_ext.rb', line 78

def squash(width)
  returning new_ary = [] do
    rows = (self.size.to_f/width + 0.49).round
    (1..rows).each do |row_num|
      new_ary << self[(width*(row_num-1))..(width*(row_num-1) + width-1)]
    end
  end
end

#strip_allObject



74
75
76
# File 'lib/array_ext.rb', line 74

def strip_all
  map!{|t| t.strip}
end

#strip_eachObject



26
27
28
# File 'lib/array_ext.rb', line 26

def strip_each
  self.map{|t| t.strip}
end

#strip_each!Object



29
30
31
# File 'lib/array_ext.rb', line 29

def strip_each!
  self.each{|t| t.strip!}
end

#to_sentenceObject



33
34
35
36
37
38
39
40
# File 'lib/array_ext.rb', line 33

def to_sentence
  i = size
  if size<=2
    self.join(" and ")
  else
    [self[0..size-2].join(", "), self[size-1]].join(" and ")
  end
end