@search_results = Array.new duplicates = Set.new results.each { |result| @search_results.push(result) unless duplicates.add?(result[:url]) }
This piece of code is garbling the order of elements in the array @search_results. Why would inserting the same element in a set and an array change the insertion order for Array? Seems like some issue with element references. Can someone explain?
Edit 1: I am using an Array. Sorry for the earlier typo. I double checked by code and it uses Array too (there is no push method for Hash anyways)
The order of elements in a Hash is not guaranteed. You’ll have to sort the keys if you want a guaranteed order.
This is supposedly fixed in Ruby 1.9 I believe.
Edit: I’m assuming your results in an Array, if its a Hash then order isn’t guaranteed and you’ll have to sort the keys, here’s what my test looks like:
If I run that, here’s the result:
I found that odd, so just to be sure, I put a
.nil?add the end of.add?and here was my result:Now that was what I was expecting: is this what you mean by ‘garbled’?
Edit 2: Upon further investigation, I think this is because of Ruby’s super strict rules when converting non-Boolean data to Booleans (see Ruby Gotchas on Wikipedia and Stack Overflow, of course) so that basically anything that only false is really false and everything else is true. so the
.nil?is converting it explicitly to true/false.