使用哈希数组我需要比较两个值

时间:2015-03-20 22:14:36

标签: ruby-on-rails ruby

我有以下哈希数组:

 [{"dwidNote"=>14, "StreetAddress"=>"250 Palm Valley Blvd.", "PropertyAddress"=>"250 Palm Valley Blvd."},
 {"dwidNote"=>16, "StreetAddress"=>"2801 Alaskan Way", "PropertyAddress"=>"2801 Alaskan Way"},
 {"dwidNote"=>17, "StreetAddress"=>"300 LAKESIDE DRIVE", "PropertyAddress"=>"300 LAKESIDE DRIVE  "},
 {"dwidNote"=>18, "StreetAddress"=>"3817 PARKDALE", "PropertyAddress"=>"3817 PARKDALE  "}]

我需要比较键StreetAddressPropertyAddress的值,看看它们是否匹配。对于不匹配的值,我需要显示键dwidNote的值。我该怎么做?

3 个答案:

答案 0 :(得分:3)

假设您的数组位于名为a的变量中,那么:

a.select{|e| e['StreetAddress'] != e['PropertyAddress']}.map{|e| e['dwidNote']}

将返回此信息:

[17, 18]

答案 1 :(得分:1)

array = [{"dwidNote"=>14, "StreetAddress"=>"250 Palm Valley Blvd.", "PropertyAddress"=>"250 Palm Valley Blvd."},
 {"dwidNote"=>16, "StreetAddress"=>"2801 Alaskan Way", "PropertyAddress"=>"2801 Alaskan Way"},
 {"dwidNote"=>17, "StreetAddress"=>"300 LAKESIDE DRIVE", "PropertyAddress"=>"300 LAKESIDE DRIVE  "},
 {"dwidNote"=>18, "StreetAddress"=>"3817 PARKDALE", "PropertyAddress"=>"3817 PARKDALE  "}]

array.map { |x|
   x["dwidNote"] if x["StreetAddress"] != x["PropertyAddress"]
}.compact

会完成这项工作

答案 2 :(得分:1)

我愿意:

arr = [{"dwidNote"=>14, "StreetAddress"=>"250 Palm Valley Blvd.", "PropertyAddress"=>"250 Palm Valley Blvd."}, {"dwidNote"=>16, "StreetAddress"=>"2801 Alaskan Way", "PropertyAddress"=>"2801 Alaskan Way"}, {"dwidNote"=>17, "StreetAddress"=>"300 LAKESIDE DRIVE", "PropertyAddress"=>"300 LAKESIDE DRIVE  "}, {"dwidNote"=>18, "StreetAddress"=>"3817 PARKDALE", "PropertyAddress"=>"3817 PARKDALE  "}]

arr.map { |h| h['dwidNote'] unless h['StreetAddress'] == h['PropertyAddress']  }.compact
#=> [17, 18]