问题描述
我正在阅读,当我在 about_hashes.rb $ c
def test_default_value_is_the_same_object
hash = Hash.new([])
hash [:one]<< uno
hash [:two]<< dos
assert_equal [uno,dos],hash [:one]
assert_equal [uno,dos],hash [:two]
assert_equal [uno,dos],hash [:three]
assert_equal true,hash [:one] .object_id == hash [:two] .object_id
end
assert_equals 中的值实际上是预期的教程。但我无法理解如何使用<< 运算符? p>
我的期望是:
为什么我的期望是错的?
当你在做 hash = Hash.new([] )您正在创建一个Hash,其默认值与所有键完全相同的Array实例。所以,当你访问一个不存在的键时,你会得到相同的数组。
h = Hash.new ([])
h [:foo] .object_id#=> 12215540
h [:bar] .object_id#=> 12215540
如果你想为每个键一个数组,你必须使用 Hash.new :
h = Hash.new {| h,k | h [k] = []}
h [:foo] .object_id#=> 7791280
h [:bar] .object_id#=> 7790760
编辑:另请参阅Gazler关于#<< 方法以及您实际调用它的对象。
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 = Hash.new([]) hash[:one] << "uno" hash[:two] << "dos" assert_equal ["uno", "dos"], hash[:one] assert_equal ["uno", "dos"], hash[:two] assert_equal ["uno", "dos"], hash[:three] assert_equal true, hash[:one].object_id == hash[:two].object_id end
The values in assert_equals, is actually what the tutorial expected. But I couldn't understand how there is a difference between using << operator and = operator?
My expectation was that:
- hash[:one] would be ["uno"]
- hash[:two] would be ["dos"]
- hash[:three] would be []
Can someone please explain why my expectation was wrong?
When you're doing hash = Hash.new([]) you are creating a Hash whose default value is the exact same Array instance for all keys. So whenever you are accessing a key that doesn't exist, you get back the very same Array.
h = Hash.new([]) h[:foo].object_id # => 12215540 h[:bar].object_id # => 12215540
If you want one array per key, you have to use the block syntax of Hash.new:
h = Hash.new { |h, k| h[k] = [] } h[:foo].object_id # => 7791280 h[:bar].object_id # => 7790760
Edit: Also see what Gazler has to say with regard to the #<< method and on what object you are actually calling it.
这篇关于shovel(<<)运算符在Ruby Hashes中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!