基于另一个哈希的ruby排序哈希

时间:2015-01-14 23:02:16

标签: ruby

我有以下两个哈希:

db = {"1" => "first_name", "2" => "last_name", "5" => "status", "10" => "city"  }
csv = {"1" => "first_name", "2" => "last_name", "5" => "status", "7" => "address", "10" => "city" }

我想基于db命令csv,如果csv中有任何键不在db中,那么我想将它们移到csv的末尾,所以在上面的例子中结果看起来像这样:

{"1" => "first_name", "2" => "last_name", "5" => "status", "10" => "city", "7" => "address" }

由于密钥“7”不在db hash中,我们只是将其移动到csv哈希的末尾。

这就是我的尝试:

db = {"1" => "first_name", "2" => "last_name", "5" => "status", "10" => "city"  }
csv = {"1" => "first_name", "2" => "last_name", "5" => "status", "7" => "address", "10" => "city" }
rejects = csv.reject {|k| db.include? k }
result = csv.keep_if {|k,_| db.include? k }
result.merge!(rejects)
result   
=> {"1"=>"first_name", "2"=>"last_name", "5"=>"status", "10"=>"city", "7"=>"address"}

似乎有效。但它能保证有效吗?合并是否总是将第二个哈希放在最后,或者合并是否有可能将哈希混合在一起而不考虑订单?

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

db_keys = db.keys
  #=> ["1", "2", "5", "10"] 
keys = db_keys + (csv.keys-db_keys)
  #=> ["1", "2", "5", "10", "7"] 
Hash[keys.zip(csv.values_at(*keys))]
  #=> { "1"=>"first_name", "2"=>"last_name", "5"=>"status",
  #    "10"=>"city", "7"=>"address"}