Skip to content

Instantly share code, notes, and snippets.

@gstark
Created July 14, 2012 06:19
Show Gist options
  • Save gstark/3109687 to your computer and use it in GitHub Desktop.
Save gstark/3109687 to your computer and use it in GitHub Desktop.
using |= to merge collections into sets is inefficient, the correct way is to use #merge
# This shows that set |= collection creates a NEW set with the resulting
# members which is slightly inefficient. #merge does the same thing
# without creating a new Set object
require 'set'
set = Set.new([1,2,3,4])
puts "set is: #{set.inspect} and Object ID before |= is #{set.object_id}"
set |= [4,5,6]
puts "set is: #{set.inspect} and Object ID after |= is #{set.object_id}"
set.merge([6,7,8])
puts "set is: #{set.inspect} and Object ID after merge is #{set.object_id}"
#set is: #<Set: {1, 2, 3, 4}> and Object ID before |= is 2240588820
#set is: #<Set: {5, 6, 1, 2, 3, 4}> and Object ID after |= is 2240588480
#set is: #<Set: {5, 6, 1, 7, 2, 8, 3, 4}> and Object ID after merge is 2240588480
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment