Class: Array
- Inherits:
-
Object
- Object
- Array
- Defined in:
- lib/bootstripe/array_additions.rb
Instance Method Summary collapse
- #compakt ⇒ Object
- #count(&action) ⇒ Object
- #mean ⇒ Object
- #random(num_elements = 1) ⇒ Object
- #random_by_frequency(seed = nil) ⇒ Object
- #randomized ⇒ Object
-
#sections(min_size, max_size) ⇒ Object
Return subarrays of random length between a min and max.
- #sum ⇒ Object
Instance Method Details
#compakt ⇒ Object
15 16 17 18 19 20 21 |
# File 'lib/bootstripe/array_additions.rb', line 15 def compakt self.reject do |i| i.nil? || (i.respond_to?(:length) && i.length == 0) || (i.respond_to?(:match) && i.match(/^\s+$/)) end end |
#count(&action) ⇒ Object
10 11 12 13 |
# File 'lib/bootstripe/array_additions.rb', line 10 def count(&action) return size unless block_given? self.inject(0){ |memo,item| memo += 1 if action.call(item); memo } end |
#mean ⇒ Object
6 7 8 |
# File 'lib/bootstripe/array_additions.rb', line 6 def mean sum / size end |
#random(num_elements = 1) ⇒ Object
23 24 25 |
# File 'lib/bootstripe/array_additions.rb', line 23 def random(num_elements = 1) num_elements == 1 ? self[Kernel.rand(size)] : sort_by{ Kernel.rand }.slice(0...num_elements) end |
#random_by_frequency(seed = nil) ⇒ Object
27 28 29 30 31 32 |
# File 'lib/bootstripe/array_additions.rb', line 27 def random_by_frequency(seed = nil) self.select{|i| i.is_a?(Hash) }.inject({}) do |memo, item| memo[item] = item['frequency'] || item[:frequency] || 0 memo end.random_by_frequency(seed) end |
#randomized ⇒ Object
34 35 36 |
# File 'lib/bootstripe/array_additions.rb', line 34 def randomized sort_by { rand } end |
#sections(min_size, max_size) ⇒ Object
Return subarrays of random length between a min and max
39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/bootstripe/array_additions.rb', line 39 def sections(min_size, max_size) sects = [] offset = 0 while offset < size next_size = (min_size..max_size).random.to_i sects << self[offset..offset+next_size] offset += next_size + 1 end sects end |
#sum ⇒ Object
2 3 4 |
# File 'lib/bootstripe/array_additions.rb', line 2 def sum self.inject(:+) end |