Skip to content

Instantly share code, notes, and snippets.

@keithrbennett
Last active October 9, 2018 23:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keithrbennett/633b30516ea3095ae7ddff24755e8f14 to your computer and use it in GitHub Desktop.
Save keithrbennett/633b30516ea3095ae7ddff24755e8f14 to your computer and use it in GitHub Desktop.
A solution to including duplicates of some classes but not others
#!/usr/bin/env ruby
# A solution to the problem where one wants to create a new array
# that includes all instances of A and B but only the first instances
# of C & D.
require 'set'
class A; end
class B; end
class C; end
class D; end
def class_duplicates_ok?(klass)
[A, B].include?(klass)
end
def prune_array(array)
classes_found = Set.new
array.each_with_object([]) do |element, pruned_array|
klass = element.class
if class_duplicates_ok?(klass) || (! classes_found.include?(klass))
pruned_array << element
end
classes_found << klass
end
end
def main
options = [A.new, B.new, A.new, B.new, C.new, C.new, D.new]
pruned = prune_array(options)
puts "\nOriginal: "; puts options
puts "\nPruned: "; puts pruned
end
main
=begin
Sample Output:
Original:
#<A:0x00007f8c81915130>
#<B:0x00007f8c81915108>
#<A:0x00007f8c819150e0>
#<B:0x00007f8c819150b8>
#<C:0x00007f8c81915018>
#<C:0x00007f8c81914ff0>
#<D:0x00007f8c81914f28>
Pruned:
#<A:0x00007f8c81915130>
#<B:0x00007f8c81915108>
#<A:0x00007f8c819150e0>
#<B:0x00007f8c819150b8>
#<C:0x00007f8c81915018>
#<D:0x00007f8c81914f28>
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment