为什么数组是没有得到Ruby的修改? [英] Why the array is not getting modified in Ruby?

查看:99
本文介绍了为什么数组是没有得到Ruby的修改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图code对IRB几行,然后我发现我不能修改一个新的数组返回从哈希的默认值。下面是一个IRB会议的更多详细信息,显示我的情况:

I was trying a few lines of code on IRB, and then I found that I could not modify a new array returned as a default value from a Hash. The following is an IRB session that shows in more details my situation:

a = Hash.new { Array.new }
#=> {}
a[2]
#=> []
a[2].push '2'
#=> ["2"]
a[2]
#=> []
a[2] = []
#=> []
a[2].push '2'
#=> ["2"]
a
#=> {2=>["2"]}
a[2].push '2'
#=> ["2", "2"]
a
#=> {2=>["2", "2"]}

为什么我不能修改一个不存在的键的默认值?

Why I cannot modify the default value of a nonexistent key?

推荐答案

哈希#新 使用这样的:

The block form of Hash#new is used like this:

b = Hash.new {|hash, key| hash[key] = Array.new}
#=> {}
b[2]
#=> []
b[2].push('2')
#=> ["2"]
b[2]
#=> ["2"]
b[3]
#=> []
b[3].push('3')
#=> ["3"]
b[3]
#=> ["3"]

这篇关于为什么数组是没有得到Ruby的修改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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