HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Comparing hash members to other hash members

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
membersothercomparinghash

Problem

I've written a script that deletes a member of a hash if an array within the has contains all the other elements of another array within the same hash.

It works but it looks a little messy. Is there a better way to do this?

def title_contains_blocks(candidate, titles, index)
  test_group = titles.dup
  test_group.delete_at(index)
  test_group.each do |title|
    return true if true === title[:blocks].all?{|block| candidate[:blocks].include?(block)}
  end

  return false
end

titles = [
  {:blocks => [1,2,3,4,5,6]},
  {:blocks => [1,2,3]},
  {:blocks => [4,5,6]}
]

titles = titles.delete_if.each_with_index {|candidate, index| 
  title_contains_blocks(candidate, titles, index)
}

puts titles.inspect
#=> [{:blocks=>[1, 2, 3]}, {:blocks=>[4, 5, 6]}]

Solution

Convert the Hashes to Arrays, then use the difference operations on them.

a = { :a => 1, :b => 2, :c => 2 }
b = { :a => 1 }

p (b.to_a - a.to_a).empty?


You can do other things, like identify if two Hashes overlap in any places, by use the intersection too:

p (a.to_a & b.to_a).any?

Code Snippets

a = { :a => 1, :b => 2, :c => 2 }
b = { :a => 1 }

p (b.to_a - a.to_a).empty?
p (a.to_a & b.to_a).any?

Context

StackExchange Code Review Q#11341, answer score: 4

Revisions (0)

No revisions yet.