为什么将字符串铲入哈希会导致此结果? [英] Why does shoveling a string into a hash cause this result?

查看:45
本文介绍了为什么将字符串铲入哈希会导致此结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究 Ruby Koans,以便更好地掌握 Ruby 和 TDD.我到了 about_hashes.rb 代码中的第 93 行,这让我困惑如何将它推入默认构造函数而不是散列值.出于好奇,我尝试使用字符串作为构造函数的参数使用相同的东西,它产生了类似的结果.

I'm working through the Ruby Koans in order to get a better grasp on Ruby and TDD. I got to Line 93 in the code in about_hashes.rb and this confuses me how it would be shoveled into the default constructor instead of the hash value. Just out of curiosity I tried using the same thing with a string as the parameter of the constructor and it produced a similar result.

现在我的问题是,为什么无论我使用什么键,都会检索到相同的对象,以及如何将新对象铲到方法中散列中特定键的数组中 test_default_value_is_the_same_object?

def test_default_value_is_the_same_object
    hash = Hash.new([])

    hash[:one] << "uno"
    hash[:two] << "dos"

    assert_equal ["uno", "dos"], hash[:one] #why not ["uno"]?
    assert_equal ["uno", "dos"], hash[:two] #why not ["dos"]?
    assert_equal ["uno", "dos"], hash[:three] #why not []?

    assert_equal true, hash[:one].object_id == hash[:two].object_id
  end

def test_default_value_with_block
    hash = Hash.new {|hash, key| hash[key] = [] }

    hash[:one] << "uno"
    hash[:two] << "dos"

    assert_equal ["uno"], hash[:one]
    assert_equal ["dos"], hash[:two]
    assert_equal [], hash[:three]
end

推荐答案

有关原因的提示在测试名称中.

A hint as to the reason is in the name of the tests.

test_default_value_is_the_same_object 是为了向您展示,当您请求 hash[:some_value_that_doesnt_exist_yet] 时,默认情况下,您会得到您指定的默认值 -- 即每次同一个对象.通过修改该对象,您可以为每个不存在的键修改它.修改 hash[:one] 也会修改 hash[:two].

test_default_value_is_the_same_object is there to show you that when you ask for hash[:some_value_that_doesnt_exist_yet], by default, you get back the default value you specified -- which is the same object every time. By modifying that object, you modify it for every nonexistent key. Modifying hash[:one] also modifies hash[:two].

test_default_value_with_block 展示了使用区块构建哈希的过程,该区块将用于为每个键提供一个新值.当你这样做时,hash[:one]hash[:two] 的值是不同的.

test_default_value_with_block shows the construction of a Hash using a block, which will be used to provide a new value for each key. When you do it like that, the values for hash[:one] and hash[:two] are distinct.

这篇关于为什么将字符串铲入哈希会导致此结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆