rwb
rwb

Reputation: 4478

Comparing two arrays of hashes using sets in Ruby

Following this SO I am trying to compare two arrays of hashes:

db = [
{:foo => "bar", :stack => "overflow", :num => 0.5},
{:foo => "bar", :stack => "underlow", :num => 0.5},
{:foo => "bar", :stack => "overflow", :num => 0.1}
]

csv = [
{:foo => "bar", :stack => "overflow", :num => 0.5},
{:foo => "bar", :stack => "underlow", :num => 0.1},
]
 

I am trying to use a Ruby Set (db_set = Set[db], csv_set = Set[csv]) to compare the two using - (db_set - csv_set) and & (db_set & csv_set) but these do not appear to be performing the compare operations.

Have i misunderstood the use of Set? How can i compare these two arrays of hashes?

Upvotes: 1

Views: 3635

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230386

No need to use sets here. Seems that you'll be good with Array operators.

db = [
  {:foo => "bar", :stack => "overflow", :num => 0.5},
  {:foo => "bar", :stack => "underlow", :num => 0.5},
  {:foo => "bar", :stack => "overflow", :num => 0.1}
]

csv = [
  {:foo => "bar", :stack => "overflow", :num => 0.5},
  {:foo => "bar", :stack => "underlow", :num => 0.1},
]

db - csv # => [{:foo=>"bar", :stack=>"underlow", :num=>0.5}, {:foo=>"bar", :stack=>"overflow", :num=>0.1}]
db & csv # => [{:foo=>"bar", :stack=>"overflow", :num=>0.5}]

Upvotes: 4

Related Questions