str = 

RE = /(?<word1>[a-zA-Z]+)\s+(?<word2>[a-zA-Z]+)/
str = str.upcase

2.times{ str.gsub!(RE){ [  $~[:word1], $~[:word1].size, $~[:word2] ].join()} }

table = Hash[*str.split].transform_values(&:to_i)

test =  
ar = test.split.map do |w|
  (res = table.detect{|k,v| k.start_with?(w.upcase) && w.size >= v})? res[0]: 
end

puts ar.join()