无法理解ruby如何打印此哈希

时间:2021-07-01 20:53:10

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:

    我使用了irb并在其中创建了一个简单的哈希sampleHash = {“One”=> 1,“Two”=> 2,“Three”=> 3}但是当它存储它时(它显示你按下返回键后) ),这就是我得到的=> {“一个”=> 1,“三个”=> 3,“两个”=> 2}。当我像这样打印出来时:sampleHash.each do | count,num | print“#{count}:#{num} \ n”end我得到这个作为输出:

    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?

它如何存储密钥和值?为什么以不同的方式打印它?我在这里想念的是什么?

1 个解决方案

#1


3  

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.

在Ruby 1.9之前的哈希是无序的。也就是说,将键插入哈希的顺序与迭代哈希时出现的顺序无关。

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.

没有办法通过内置哈希来修复这个问题,而不是升级到Ruby 1.9。如果需要维护其键的顺序的哈希,可以使用ActiveSupport :: OrderedHash。

#1


3  

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.

在Ruby 1.9之前的哈希是无序的。也就是说,将键插入哈希的顺序与迭代哈希时出现的顺序无关。

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.

没有办法通过内置哈希来修复这个问题,而不是升级到Ruby 1.9。如果需要维护其键的顺序的哈希,可以使用ActiveSupport :: OrderedHash。