Kevin Colwell
Kevin Colwell

Reputation: 11

Using an array of hashes I need to compare two values

I have the following array of hashes:

 [{"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  "}]

I need to compare the values for the keys StreetAddress and PropertyAddress to see if they match. For the values that do not match I need to display the value for key dwidNote. How do I do this?

Upvotes: 1

Views: 52

Answers (3)

xlembouras
xlembouras

Reputation: 8295

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

would do the job

Upvotes: 1

Sharvy Ahmed
Sharvy Ahmed

Reputation: 7405

I would do:

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] 

Upvotes: 1

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

Assuming your array is in a variable named a then this:

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

will return this:

[17, 18]

Upvotes: 3

Related Questions