Ruby 根据某些条件为每个值匹配区域

Ruby 根据某些条件为每个值匹配区域,ruby,compare,match,Ruby,Compare,Match,我有一个输入表,显示了与每个国家代码相关的国家代码和地区 1721 124622 124624 358 33751 599 65 1721 1

我有一个输入表,显示了与每个国家代码相关的国家代码和地区


1721

124622

124624

358

33751

599

65

1721

1

def count_equal_digits_at_beginning(a, b) return a.size if a == b rabdiff = (a.reverse.to_i - b.reverse.to_i).abs rabdiff.digits.count - rabdiff.to_s.reverse.to_i.digits.count end

mapping_hash = cc.reverse.zip(zones.reverse).to_h
res = numbers.map.with_object([]) do |n, res|
  exact = cc.find { |c| c == n }
  if exact
    found = exact
  else
    tmp = cc.map { |c| [c, count_equal_digits_at_beginning(c, n)] }
    possibles = tmp.find_all { |c, count| count == tmp.max_by(&:last).last && count > 1 }
    good = possibles.sort_by(&:first).reverse.first
    found = good.first if good
  end
  res << [ n, mapping_hash[found] || "not found" ]
end.to_h
res #=> {"18763044"=>"JAM", "187635"=>"JAM", "23092"=>"MUS", "3162"=>"NLD", "38050"=>"not found", "33"=>"FRA1", "49185"=>"not found", "51078"=>"not found", "1246"=>"BRB7", "1721"=>"SXM2"}