开发者

Stuffing Hash in Array behaves differently using "var" rather than :var -- why?

Why do these snippets of code behave differently? I thought they were supposed to do the same thing...

    foo = {}
    array = []

    foo['a'] = "1"
    foo['b'] = 开发者_如何转开发"2"

    array << foo

    foo['a'] = "3"
    foo['b'] = "4"

    array << foo

    output => [{"a"=>"3", "b"=>"4"}, {"a"=>"3", "b"=>"4"}]

This is not what I want. Fortunately, I tried using this format, which works:

    foo = {}
    array = []

    foo = {
        :a => "1",
        :b => "2"
    }

    array << foo

    foo = {
        :a => "3",
        :b => "4"
    }

    array << foo

    output => [{:a=>"1", :b=>"2"}, {:a=>"3", :b=>"4"}]

What's going on here?


It's not " vs. : — it's that you're modifying foo (foo[...]=...) in the first example while you're reassigning the variable foo (foo=...) in the second. In the first example, foo still refers to the same object (which is also in the array) after you put in the values 3 & 4.

For a solution, I recommend the second option (which you can use with '/" (strings) or : (symbols), no matter), or alternatively you can do array << foo.clone to push a copy of foo onto the array, so further modifications won't change it.


In your first example, you push foo itself into the array. When you edit foo on the next few lines, you are editing the same hash which you just pushed into the array!

In your second example, you explicitly set foo to a new hash using the '{}' operators. So when you set the values of 'a' and 'b', you don't touch the original foo already pushed into the array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜