noMAD
noMAD

Reputation: 7844

Can't understand how ruby prints this hash

I am a newbie with ruby and was trying out something small. So this is what I did.

  1. I used irb and in it I created a simple hash sampleHash = {"One" => 1, "Two" => 2, "Three" => 3} but when it stores it (it shows your after you press the return key), this is what I get => {"One"=>1, "Three"=>3, "Two"=>2}. Also when I print it out like this: sampleHash.each do|count, num| print "#{count}: #{num} \n" end I get this as the output:

    One: 1 
    Three: 3 
    Two: 2 
    
  2. Now, I tried it using the editor, this is what I wrote:

    hashExample = {"One" => 1,
                   "Two" => 2,
                   "Three" => 3 }
    hashExample.each do|count, num|
      print "#{count}: #{num} \n"
    end
    

    I get this as the output:

    Three: 3 
    Two: 2 
    One: 1
    

How does it store the keys and values? Why is it printing it in different ways? What am I missing here?

Upvotes: 1

Views: 78

Answers (1)

user229044
user229044

Reputation: 239521

Hashes, prior to Ruby 1.9, are unordered. That is, the order that you insert keys into the hash has nothing to do with the order they come out when you iterate over the hash.

There isn't a way to fix this with built-in hashes short of upgrading to Ruby 1.9. If you need a hash which maintains the order of its keys, you can use ActiveSupport::OrderedHash.

Upvotes: 3

Related Questions