Method: Array#prefix

Defined in:
lib/snmputils/arrayutils.rb

#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