Sunday 15 January 2012

Is there a simple way to iterate through pairs in a Ruby hash in order of addition (i.e. oldest first)? -


I make an empty hash chickens , and periodically add key-value Go. ("Mortimer" = & gt; "Sullen") Chickens. Merge! ("Chounese!") For the name "=", "follon"), the mood in chickens says, "# {name}: # {mood}" and

  Mortimer: Sullen Chounsii: Nostalgic Davison: Hello   

But I do not want this. How were I added to the order through chicken?

The short answer is: Update your ruby. Ruby is 1.9 years old and works the way you want (as current Ruby, 2.0) works. If you insist on the ancient, unsupported ruby, then there is an ordered hash class available through a Murder:

  gem installed order   

Your code then Will become:

  'rubygems' requires 'orderhash' chickens = hash ordered. New # The rest remains the same   

Again, I only recommend upgrading your Ruby installation.

Your code will be too much more like Ruby if you will iterate over the hash like this:

  chickens. Name, mood | Puts "# {name}: # {mood}" end    

No comments:

Post a Comment