On Jan 14, 2011, at 5:39 PM, Jamal S. wrote:
How can I intersection and union based on the conditions in the hash
through them all?
So it end up like this
array = rule[:array] & rule2[:array] | rule3[:array]
Let me rephrase that because you still aren’t giving enough
information to really know what you’re trying to do.
Given an array of hashes:
input = [ {:array => [1,2,3,4], :condition => “AND”},
{:array => [2,4,6,8], :condition => “OR”},
{:array => [1,3]},
]
array = input[0][:array] & input[1][:array] | input[2][:array]
=> [2, 4, 1, 3]
Well, if you apply the operations serially, you will actually get
something like:
array = ((input[0][:array] & input[1][:array]) | input[2][:array])
Since & is higher precendence than |, the answer is the same, but if
you change the order:
array = input[0][:array] | input[1][:array] & input[2][:array]
=> [1, 2, 3, 4]
is not the same as:
array = ((input[0][:array] | input[1][:array]) & input[2][:array])
=> [1, 3]
def combine(arrays)
result, op = [], “OR”
arrays.each do |hsh|
case op
when “OR”
result |= hsh[:array]
when “AND”
result &= hsh[:array]
end
op = hsh[:condition]
end
result
end
combine(input)
#=> [2, 4, 1, 3]
-Rob
Rob B.
[email protected] http://AgileConsultingLLC.com/
[email protected] http://GaslightSoftware.com/