加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

这个ruby片段如何工作?

发布时间:2020-12-17 03:41:05 所属栏目:百科 来源:网络整理
导读:难题: something = {}another = something('a'...'f').each do |x| puts "another = #{another} and x= #{x} and something = #{something}" another = (another[x] ||= {})endputs something 输出: =another = {} and x= a and something = {}=another =
难题:

something = {}
another = something
('a'...'f').each do |x|
  puts "another = #{another} and x= #{x} and something = #{something}"
  another = (another[x] ||= {})
end
puts something

输出:

=>another = {} and x= a and something = {}
=>another = {} and x= b and something = {"a"=>{}}
=>another = {} and x= c and something = {"a"=>{"b"=>{}}}
=>another = {} and x= d and something = {"a"=>{"b"=>{"c"=>{}}}}
=>another = {} and x= e and something = {"a"=>{"b"=>{"c"=>{"d"=>{}}}}}

现在乍一看它看起来像’另一个’和’某事’都指向相同的哈希对象,但如果是这种情况,那么在输出’另一个’将匹配’某事’.那么变量’something’如何不是空哈希?

解决方法

在Ruby中,一切都是一个对象,所有对象都是使用指针传递的(有例外,但这里不适用).当你这样做

something = {}
another = something

创建单个Hash对象,并且两个变量都指向同一个对象.当你这样做

another[x] ||= {}

创建一个Hash对象,并将指向该对象的指针添加到另一个指向的Hash.另一种写作方式是

old_hash = another
new_hash = {}
old_hash[x] = new_hash
another = new_hash

请记住:所有这些任务都只是移动指向对象的指针.现在应该清楚另一个指向新的(空)哈希.但是,由于old_hash还包含指向新哈希的指针,因此old_hash将看到对新哈希(即另一个)的任何期货更改.这就是为什么每次迭代都会增长的原因.

你的例子与这种简单的情况没什么不同:

x = {}
y = {}
z = {}
x["a"] = y
y["b"] = z
z["c"] = {}
puts x
# {"a"=>{"b"=>{"c"=>{}}}}

您的示例只是反转最后三个分配 – 这对结果没有影响.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读