Skip to content

Instantly share code, notes, and snippets.

@radiosilence
Created January 16, 2019 20:13
Show Gist options
  • Save radiosilence/fe7ad63c3cb5739829fa94a6a9cbb8dc to your computer and use it in GitHub Desktop.
Save radiosilence/fe7ad63c3cb5739829fa94a6a9cbb8dc to your computer and use it in GitHub Desktop.
myArray = [{:key => nil, :x => nil}, {:z => nil}, {:potato => "hi", :deep => {:deep => {:deep => "asf" } } } ]
print myArray
print "\n"
potato = "hi"
# IMMUTABLE VERSION: make a new array but with hashes that are either the same exact hash or an updated version
myArray2 = myArray.map do |hash|
hash.key?(:key) ? hash.merge({:key => potato}) : hash
end
print myArray2
print "\n"
# MUTABLE VERSION: MMmake a new array for comparison but just mutate the hash if it has the key
myArray3 = []
myArray.each do |hash|
if hash.key?(:key)
hash[:key] = potato
end
myArray3.push(hash)
end
print myArray3
print "\n"
print myArray
# here we try compare whether the merged hashes are the same
myArray2.each_index do |idx|
print "\n"
print myArray2[idx].equal? myArray[idx] # can do a reference comparison that is O(1)
end
# here we try compare whether the mutated hashes are the same"
myArray3.each_index do |idx|
print "\n"
print myArray2[idx] == myArray[idx] # always returns true , would have to do a deep check
end
print "\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment