Home > Mobile >  Filtering when adding elements by id
Filtering when adding elements by id

Time:10-30

Tell me how to do this, where you can read about it, because I do not understand at all how to implement it. Thanks.

def initialize
  @arr = []
end

def items(init)
  arrfinish = init - @arr
  @arr = (@arr   init).uniq
  yield arrfinish
end

def idefine(find_text)

end

The class has a method(items) that connects arrays by removing duplicate elements. I need to make sure that the idefine method receives the key by which filtering will be performed when adding new elements, I will give an example below.

app_handler.idefine('id')
app_handler.items([{'id' => 1}, {'id' => 1, 'test_key' => 'Some data'}, {'id' => 2}])

From this example, the second element with id = 1 should be ignored.

CodePudding user response:

Ok, putting aside the class definition, what I understand of the question is:
In an array of hashes, remove the hashes that contain a duplicated value of a given key.

The following function filter the hashes and copy the content of the selected ones in a new array:

require 'set'

def no_dup_val key, arr
  previous_values = Set[]
  arr.each_with_object([]) do |hash,result|
    next unless hash.has_key?(key)
    next if previous_values.include?(hash[key])
    previous_values << hash[key]
    result << hash.dup
  end
end

Which gives you:

no_dup_val 'id', [{'id' => 1}, {'id' => 1, 'key' => 'data'}, {'id' => 2}, {'stock' => 3}, {'e-stock'=>0}]
#=> [{"id"=>1}, {"id"=>2}]

Note that the hashes that don't contain the key are also removed, that's my choice, which leads to the following questions:

  • What happens when the key is not present in a hash?
  • What happens when the item function is called more than once? Do you take into account the hashes already in @arr?
  • What happens when you call idefine with a new key? Do you filter the existing elements of @arr with the new key?

As you can see, you need to be a little more specific about what you want to do.


Update

If you don't care about copying the contents of the hashes then these may fit your needs.

  1. Hashes without the id key are removed:
def no_dup_val key, arr
  arr.filter{ |h| h.has_key?(key) }.uniq{ |h| h[key] }
end

no_dup_val 'id', [{'id' => 1}, {'id' => 1, 'key' => 'data'}, {'id' => 2}, {'stock' => 3}, {'e-stock'=>0}]
#=> [{"id"=>1}, {"id"=>2}]
  1. Hashes without the id key are treated as having "id" => nil (so the first will be kept):
def no_dup_val key, arr
  arr.uniq{ |h| h[key] }
end

no_dup_val 'id', [{'id' => 1}, {'id' => 1, 'key' => 'data'}, {'id' => 2}, {'stock' => 3}, {'e-stock'=>0}]
#=> [{"id"=>1}, {"id"=>2}, {"stock"=>3}]
  1. All the hashes without the id key are kept:

  •  Tags:  
  • ruby
  • Related