Class: Array

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

Instance Method Summary collapse

Instance Method Details

#biggestObject

Returns the biggest, i.e. greatest, non-nil element



19
20
21
22
# File 'lib/ndr_support/array.rb', line 19

def biggest
  # self.compact.sort.last
  self.compact.max
end

#permutationsObject

Finds all the permutations of the array:

[1,2,3].permutations #=> [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]
[3,3].permutations   #=> [3,3], [3,3]


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/ndr_support/array.rb', line 35

def permutations
  return [self] if length == 1

  orders = []
  positions = (0...length).to_a

  # Finding the permutations with a basic array of digits
  positions.each do |position|
    (positions - [position]).permutations.each do |permutation|
      orders << permutation.unshift(position)
    end
  end

  # We subsitute in our original elements. This prevents duplicate
  # elements from causing problems, and allows the [3,3] example to work.
  orders.map { |order| order.map { |index| self[index] } }
end

#ranges_include?(value) ⇒ Boolean

Flattens range objects within an array to allow include? to work within the array and within the ranges within the array.

Returns:

  • (Boolean)


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

def ranges_include?(value)
  any? { |range| Array(range).include?(value) }
end

#smallestObject

Returns the smallest, i.e. least, non-nil element (can be used for any type of object that supports the <=> operator, including dates)



13
14
15
16
# File 'lib/ndr_support/array.rb', line 13

def smallest
  # self.compact.sort.first
  self.compact.min
end

#values_matching(a) ⇒ Object

A utility method to return those elements in an array where the item in a corresponding array in true (matching by index)



4
5
6
7
8
9
# File 'lib/ndr_support/array.rb', line 4

def values_matching(a)
  return [] unless a.respond_to?(:[])
  result = []
  each_with_index { |x, i| result << x if a[i] }
  result
end