如果密钥的顺序不一致,有没有办法比较2哈希?例如红宝石比较2哈希
hash1 = { "it"=> 10,"was"=>11,"the"=>14,"best"=>1,"of"=>12,"times"=>2,
"worst"=>1,"age"=>2,"wisdom"=>1,"foolishness"=>1,"epoch"=>2,
"belief"=>1,"incredulity"=>1,"season"=>2,"light"=>1,"darkness"=>1,
"spring"=>1,"hope"=>1,"winter"=>1,"despair"=>1,"we"=>4,"had"=>2,
"everything"=>1,"before"=>2,"us"=>2,"nothing"=>1,"were"=>2,"all"=>2,
"going"=>2,"direct"=>2,"to"=>1,"heaven"=>1,"other"=>1,
"way"=>1,"in"=>2,"short"=>1,"period"=>2,"so"=>1,"far"=>1,"like"=>1,
"present"=>1,"that"=>1,"some"=>1,"its"=>2,"noisiest"=>1,
"authorities"=>1,"insisted"=>1,"on"=>1,"being"=>1,
"received"=>1,"for"=>2,"good"=>1,"or"=>1,"evil"=>1,"superlative"=>1,
"degree"=>1,"comparison"=>1,"only"=>1 }
hash2 = {"superlative"=>1, "it"=>10, "going"=>2, "spring"=>1, "age"=>2,
"despair"=>1, "received"=>1, "good"=>1, "some"=>1, "worst"=>1, "was"=>11,
"only"=>1,"us"=>2, "evil"=>1, "belief"=>1, "for"=>2, "darkness"=>1,
"comparison"=>1, "short"=>1, "in"=>2, "present"=>1, "direct"=>2, "were"=>2,
"way"=>1, "degree"=>1, "or"=>1, "of"=>12, "epoch"=>2, "incredulity"=>1,
"period"=>2, "heaven"=>1, "other"=>1, "being"=>1, "its"=>2, "so"=>1,
"authorities"=>1, "times"=>2, "we"=>4, "noisiest"=>1, "light"=>1, "hope"=>1,
"foolishness"=>1, "everything"=>1, "far"=>1, "wisdom"=>1, "season"=>2, "like"=>1,
"before"=>2, "had"=>2, "the"=>14, "nothing"=>1, "winter"=>1, "best"=>1,
"that"=>1, "all"=>2, "insisted"=>1, "to"=>1, "on"=>1}
每个散列具有相同的键。我将如何去比较它们并确保每个关键值是正确的。我所见过的所有问题和答案都以相同的顺序显示密钥。有关系吗?
我试着使用:
hash1_1 = hash1.select{|k,_| hash2.has_key? k}
它吐了出来:
{ "it"=>10, "was"=>11, "the"=>14, "best"=>1, "of"=>12, "times"=>2,
"worst"=>1, "age"=>2, "wisdom"=>1, "foolishness"=>1, "epoch"=>2,
"belief"=>1, "incredulity"=>1, "season"=>2, "light"=>1,
"darkness"=>1, "spring"=>1, "hope"=>1, "winter"=>1, "despair"=>1,
"we"=>4, "had"=>2, "everything"=>1, "before"=>2, "us"=>2, "nothing"=>1,
"were"=>2, "all"=>2, "going"=>2, "direct"=>2, "to"=>1, "heaven"=>1,
"other"=>1, "way"=>1, "in"=>2, "short"=>1, "period"=>2, "so"=>1, "far"=>1,
"like"=>1, "present"=>1, "that"=>1, "some"=>1, "its"=>2, "noisiest"=>1,
"authorities"=>1, "insisted"=>1, "on"=>1, "being"=>1, "received"=>1,
"for"=>2, "good"=>1, "or"=>1, "evil"=>1, "superlative"=>1, "degree"=>1,
"comparison"=>1, "only"=>1}
请帮我解释什么,我需要做的。谢谢。
具有相同的键/值对
感谢帮助。 – 2014-10-09 19:03:15
即使认为这种行为是有记录的,不同的关键顺序的两个哈希应该被认为是平等的吗?它可能是一个兼容性“功能”,但概念上看起来很可疑。 – tokland 2014-10-09 19:16:48
直到最近,哈希都没有保留插入顺序,所以为了兼容性的原因,比较成立。 – tadman 2014-10-09 19:23:05