Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/snmputils/arrayutils.rb

Instance Method Summary collapse

Instance Method Details

#prefixObject

Calculate the longest common prefix for all elements in the array.

Requires array elements to support size and take operations

Examples:

[‘a’, ‘b’], [‘a’, ‘b’, ‘c’, ‘d’], [‘a’, ‘b’, ‘e’, ‘f’]].prefix # => [‘a’, ‘b’

Returns:

  • (Object)

    The largest common prefix for all elements in the array



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/snmputils/arrayutils.rb', line 22

def prefix
  pairwise_prefix = lambda do |short, long|
    if short.size == 0 or long .size == 0
      short.class.new
    else
      if short.size > long.size
        pairwise_prefix.call(long, short)
      elsif short == long.take(short.size)
        short
      else
        pairwise_prefix.call(short.take(short.size - 1), long)
      end
    end
  end
  reduce &pairwise_prefix
end

#secondObject

Convenience method to return the second element in the list

Examples:

[‘a’, ‘b’, ‘c’].second # => ‘b’

Returns:

  • (Object)

    The second object in the array



11
12
13
# File 'lib/snmputils/arrayutils.rb', line 11

def second
  return at(1)
end

#suffixObject

Calculate the longest common suffix for all elements in the array.

Requires array elements to support size and take operations

Examples:

[‘y’, ‘z’], [‘w’, ‘x’, ‘y’, ‘z’], [‘u’, ‘v’, ‘y’, ‘z’]].suffix # => [‘y’, ‘z’

Returns:

  • (Object)

    The largest common suffix for all elements in the array



46
47
48
49
# File 'lib/snmputils/arrayutils.rb', line 46

def suffix 
  prefix = (map { |x| x != nil && x.reverse }).prefix
  prefix.reverse if prefix
end