未使用哈希默认值 [英] Hash default value not being used

查看:120
本文介绍了未使用哈希默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我尝试了下面的代码片段,我不明白为什么我会在它们之间得到不同的结果。据我所知,它们是相同的。



其中一个使用默认值off Hash ,另一个片段在密钥被访问之前,为该密钥创建一个空数组。



任何了解正在发生的事情的人? :)

 #如果键值没有设置,哈希默认值为空Array 
a = Hash。新([])
a [:key]<< 2#=> [2]
p a#=> {} nil
p a [:key]#=> [2]
p a.keys#=> []
p a.values#=> []

#在创建
b = Hash.new
b [:key] || = []
b [:key]之前,为所有节点显式添加一个数组< ;< 2#=> [2]
p b#=> {:key => [2]}
p b.keys#=> [:key]

Ruby版本1.8.7

解决方案

当您完成 a [:key]<< 2 ,你将这个空的数组默认值输出并添加2(修改实际数组,而不是引用),而不让哈希对象 a 知道你改变了任何东西。您修改了 a 当前使用的对象,所以您也会看到:

  pa [:wat]#=> [2] 
p a [:anything]#=> [2]

在第二个示例中,您创建了一个新数组,并使用 b [:key] = 它告诉 b 它在该键下有一个值。



如果您想要两全其美:

  c = Hash.new([])
c [:key] + = [2]

这将访问 c [:key] 并用 + 创建一个新数组,并重新分配它。


Today I tried the following snippets of code and I don't understand why I get different results between them. As far as I can understand they are the same.

One uses the default value off Hash and the other snippet creates an empty array for the key before it'll be accessed.

Anyone who understands what's going on? :)

# Hash default if the key doesn't have a value set is an empty Array
a = Hash.new([])
a[:key] << 2 # => [2]
p a # => {} nil
p a[:key] # => [2]
p a.keys # => []
p a.values # => []

# Explicitly add an array for all nodes before creating
b = Hash.new
b[:key] ||= []
b[:key] << 2 # => [2]
p b # => {:key=>[2]}
p b.keys # => [:key]

Ruby version 1.8.7

解决方案

When you did a[:key] << 2, you slipped that empty array default value out and added 2 to it (modifying the actual array, not the reference) without letting the hash object a know that you had changed anything. You modified the object that a was using as a default, so you will see this as well:

p a[:wat] #=> [2]
p a[:anything] #=> [2]

In the second example, you made a new array, and use b[:key]= which tells b that it has a value under that key.

Try this if you want the best of both worlds:

c = Hash.new([])
c[:key] += [2]

This will access c[:key] and make a new array with + and reassign it.

这篇关于未使用哈希默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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