How does shovel (<<) operator work in Ruby Hashes?

后端 未结 2 1342
情歌与酒
情歌与酒 2020-12-04 12:06

I was going through Ruby Koans tutorial series, when I came upon this in about_hashes.rb:

def test_default_value_is_the_same_object
  hash = Has         


        
2条回答
  •  日久生厌
    2020-12-04 12:46

    You have mixed up the way this works a bit. First off, a Hash doesn't have a << method, that method in your example exists on the array.

    The reason your code is not erroring is because you are passing a default value to your hash via the constructor. http://ruby-doc.org/core-1.9.3/Hash.html#method-c-new

    hash = Hash.new([])
    

    This means that if a key does not exist, then it will return an array. If you run the following code:

    hash = {}
    hash[:one] << "uno"
    

    Then you will get an undefined method error.

    So in your example, what is actually happening is:

    hash = Hash.new([])
    
    hash[:one] << "uno"   #hash[:one] does not exist so return an array and push "uno"
    hash[:two] << "dos"   #hash[:two] does not exist, so return the array ["uno"] and push "dos"
    

    The reason it does not return an array with one element each time as you may expect, is because it stores a reference to the value that you pass through to the constructor. Meaning that each time an element is pushed, it modifies the initial array.

提交回复
热议问题