Код
def pairs?(h, suffix1, suffix2)
h1 = select(h, suffix1).transform_keys do |k|
case k
when Symbol
k.to_s.sub(/#{suffix1}\z/, suffix2).to_sym
else # String
k.sub(/#{suffix1}\z/, suffix2)
end
end
h2 = select(h, suffix2)
h1.all? { |k,v| h2[k] == v }
end
def select(h, suffix)
h.select { |k,_| k.to_s.end_with?(suffix) }
end
Примеры
h = {
"id_BEFORE"=>10825,
"id_AFTER" =>10828,
:entry1_ipnexthop_BEFORE => "10.70.230.72",
:entry1_ipnexthop_AFTER => "10.70.230.72",
"name_BEFORE" => "management",
"name_AFTER" => "management",
"prefix_BEFORE" => "10.70.230.0/24",
"prefix_AFTER" => "10.70.230.0/24",
"1_more_AFTER" => "fake value"
}
pairs?(h, "_BEFORE", "_AFTER")
#=> false
pairs?(h.merge("id_AFTER"=>10825), "_BEFORE", "_AFTER")
#=> true
Объяснение
Обратите внимание, что Hash # select (в отличие от Enumerable # select ) возвращает хэш.
Для h
, как определено в примерах, выполняются следующие шаги.
suffix1 = "_BEFORE"
suffix2 = "_AFTER"
g = select(h, suffix1)
#=> {"id_BEFORE"=>10825, :entry1_ipnexthop_BEFORE=>"10.70.230.72",
# "name_BEFORE"=>"management", "prefix_BEFORE"=>"10.70.230.0/24"}
h1 = g.transform_keys do |k|
case k
when Symbol
k.to_s.sub(/#{suffix1}\z/, suffix2).to_sym
else # String
k.sub(/#{suffix1}\z/, suffix2)
end
end
#=> {"id_AFTER"=>10825, :entry1_ipnexthop_AFTER=>"10.70.230.72",
# "name_AFTER"=>"management", "prefix_AFTER"=>"10.70.230.0/24"}
h2 = select(h, suffix2)
#=> {"id_AFTER"=>10828, :entry1_ipnexthop_AFTER=>"10.70.230.72",
# "name_AFTER"=>"management", "prefix_AFTER"=>"10.70.230.0/24",
# "1_more_AFTER"=>"fake value"}
h1.all? { |k,v| h2[k] == v }
#=> false
Enumerable # all? возвращает false
, посколькуh2[k] == v #=> false
когда k #=> "id_AFTER
(т. Е. h2[k] #=> 10828
) и v #=> 10825
.
Если мы изменим значение h["id_AFTER"]
на 10825
true
, будет возвращено:
h2 = select(h.merge("id_AFTER"=>10825), suffix2)
#=> {"id_AFTER"=>10825, :entry1_ipnexthop_AFTER=>"10.70.230.72",
# "name_AFTER"=>"management", "prefix_AFTER"=>"10.70.230.0/24",
# "1_more_AFTER"=>"fake value"}
h1.all? { |k,v| h2[k] == v }
#=> true h1.all? { |k,v| h2[k] == v }