shovel (<<) 操作符如何在 Ruby Hashes 中工作? [英] How does shovel (<<) operator work in Ruby Hashes?

查看:12
本文介绍了shovel (<<) 操作符如何在 Ruby Hashes 中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Ruby Koans 教程系列,当我在 about_hashes.rb 中发现这个时:>

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

assert_equals 中的值实际上是教程所期望的.但我不明白使用 << 运算符和 = 运算符之间有什么区别?

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?

我的期望是:

  • hash[:one] 将是 ["uno"]
  • hash[:two] 将是 ["dos"]
  • hash[:three] 将是 []
  • hash[:one] would be ["uno"]
  • hash[:two] would be ["dos"]
  • hash[:three] would be []

有人可以解释为什么我的期望是错误的吗?

Can someone please explain why my expectation was wrong?

推荐答案

当你在做 hash = Hash.new([]) 你正在创建一个默认值完全相同的哈希所有键的数组实例.因此,每当您访问一个不存在的密钥时,您都会返回相同的数组.

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

如果你想每个键一个数组,你必须使用Hash.new的块语法:

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

另请参阅 Gazler 对 #<< 方法以及您实际调用它的对象的看法.

Also see what Gazler has to say with regard to the #<< method and on what object you are actually calling it.

这篇关于shovel (&lt;&lt;) 操作符如何在 Ruby Hashes 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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