Class: Array

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

Overview

Small extensions to the Array class.

Instance Method Summary (collapse)

Instance Method Details

- (Object) chunk(length)

Splits an array into an array-of-arrays of the defined length.

Examples:

"[1,2,3,4,5,6,7,8,9,10].chunk(5)"       => "[[1,2,3,4,5],[6,7,8,9,10]]"
"[1,2,3,4,5,6,7,8,9,10,11,12].chunk(5)" => "[[1,2,3,4,5],[6,7,8,9,10],[11,12]]"

Parameters:

  • length (Integer)

    The size of the chunks to be created

See Also:

Author:

  • _why



15
16
17
18
19
20
21
22
# File 'lib/martsearch/array.rb', line 15

def chunk( length )
  chunks = []
  self.each_with_index do |element,index|
    chunks << [] if index % length == 0
    chunks.last << element
  end
  chunks
end

- (Object) clean_hashes

Helper function for Hash#clean_hashes - just call .clean_hashes if one of the elements of the array is an instance of Hash (or one of its children).



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/martsearch/array.rb', line 55

def clean_hashes
  self.map do |item|
    if item.is_a?(Hash)
      item.clean_hash
    elsif item.is_a?(Array)
      item.clean_hashes
    else
      item
    end
  end
end

- (Array) randomly_pick(number)

Randomises an array returns the defined number of elements.

If number is greater than the size of the array, the method will simply return the array itself sorted randomly.

Examples:

"[1,2,3,4,5,6,7,8,9,10,11,12].randomly_pick(3)" => "[3,12,7]"

Parameters:

  • number (Integer)

    The number of elements to return

Returns:

  • (Array)

    The randomised array



49
50
51
# File 'lib/martsearch/array.rb', line 49

def randomly_pick( number )
  sort_by{ rand }.slice( 0...number )
end

- (Object) recursively_stringify_keys!

Recursivley converts the keys of all contained hashes to strings.



34
35
36
37
38
# File 'lib/martsearch/array.rb', line 34

def recursively_stringify_keys!
  self.each do |item|
    item.recursively_stringify_keys! if item.respond_to?(:recursively_stringify_keys!)
  end
end

- (Object) recursively_symbolize_keys!

Recursivley converts the keys of all contained hashes to symbols.



26
27
28
29
30
# File 'lib/martsearch/array.rb', line 26

def recursively_symbolize_keys!
  self.each do |item|
    item.recursively_symbolize_keys! if item.respond_to?(:recursively_symbolize_keys!)
  end
end