The actual problem I was originally doing was converting a hash of arrays into an array of hashes. If anyone has any comments on doing the conversion then that's fine but the actual question I have is why the order of the hash keys change after editing them.
I'm fully aware of this question but this is not a duplicate. In fact I'm just having specific toruble in the order they are comin开发者_运维知识库g out in.
I have one array and one hash.
The array (@headers) contains a list of keys. @contents is a Hash filled with arrays. As explained, my task is to get an Array of hashes. So here's my code, pretty straightforward.
@headers = (params[:headers])
puts "ORIGINAL PARAMS"
puts YAML::dump(@headers)
@contentsArray = [] #The purpose of this is to contain hashes of each object
@contents.each_with_index do |page,contentIndex|
@currentPage = Hash.new
@headers.each_with_index do |key, headerIndex|
@currentPage[key] ="testing"
end
puts YAML::dump(@currentPage)
@contentsArray[contentIndex] =@currentPage
end
puts "UPDATED CONTENTS"
puts YAML::dump(@contentsArray[0])
Heres the bit I cant wrap my head around. The keys of the original params are in a different order than the updated one.
Note the :puts "ORIGINAL PARAMS" & puts "UPDATED CONTENTS" parts. This is their output:
ORIGINAL PARAMS
---
- " Page Title "
- " WWW "
- " Description "
- " Keywords "
- " Internal Links "
- " External Links "
- " Content files "
- " Notes "
---
UPDATED CONTENTS
---
" WWW ": page
" Internal Links ": testing
" External Links ": testing
" Description ": testing
" Notes ": testing
" Content files ": testing
" Page Title ": testing
" Keywords ": testing
Why is this?
for the record. Printing @currentPage after the header loop gives this:
" WWW ": page
" Internal Links ": page
" External Links ": page
" Description ": page
" Notes ": page
" Content files ": page
" Page Title ": page
" Keywords ": page
So it must be the way the values and keys are assigned to the @currentPage and not when It goes into the array.
In Ruby 1.8+ Hashes are UNSORTED lists
The order in which you traverse a hash by either key or value may seem arbitrary, and will generally not be in the insertion order.
While in RUBY 1.9+ they are sorted in order you push items.
Hashes enumerate their values in the order that the corresponding keys were inserted.
http://apidock.com/ruby/v1_9_2_180/Hash
This is because Ruby's Hash type uses an hash table data structure internally, and hash tables do not keep track of the order of their elements.
Ruby1.9's Hash uses a linked hash table, which keeps track of the ordre of their elements.
So in Ruby1.8 hashes are unsorted, and in Ruby1.9 hashes are sorted.
精彩评论