I have a hash, created by .group_by
method, with strings as keys and AR objects as values. And I want to get rid of AR objects with duplicated field(other fields might or might not be the same).
To clarify the question I've created this snippet:
require 'ostruct'
def os_new(fid); OpenStruct.new(fid: fid, rand: rand(100)); end
a = [os_new(1), os_new(2), os_new(3)]
b = [os_new(3), os_new(3), os_new(2)]
c = [os_new(5), os_new(5), os_new(5), os_new(5)]
grouped_hash = { a: a, b: b, c: c}
grouped_hash
here is:
# {:a=>[#<OpenStruct fid=1, rand=7>, #<OpenStruct fid=2, rand=50>, #<OpenStruct fid=3, rand=13>],
# :b=>[#<OpenStruct fid=3, rand=51>, #<OpenStruct fid=3, rand=58>, #<OpenStruct fid=2, rand=88>],
# :c=>[#<OpenStruct fid=5, rand=40>, #<OpenStruct fid=5, rand=8>, #<OpenStruct fid=5, rand=45>, #<OpenStruct fid=5, rand=72>]}
Now, in result I want a hash with unique fid
s for each key:
# {:a=>[#<OpenStruct fid=1, rand=7>, #<OpenStruct fid=2, rand=50>, #<OpenStruct fid=3, rand=13>],
# :b=>[#<OpenStruct fid=3, rand=51>, #<OpenStruct fid=2, rand=88>],
# :c=>[#<OpenStruct fid=5, rand=40>]}
My solution requires several actions and looks ugly.
grouped_hash.each_value do |value|
fids = []
value.delete_if do |object|
if fids.include? object.fid
true
else
fids << object.fid
false
end
end
end
I am looking for the most elegant(possibly 1-liner) and efficient way(without hash re-creation).