为什么 array.each 行为取决于 Array.new 语法? [英] Why does array.each behavior depend on Array.new syntax?

查看:41
本文介绍了为什么 array.each 行为取决于 Array.new 语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Ruby 1.9.2-p290 并发现:

I'm using Ruby 1.9.2-p290 and found:

a = Array.new(2, []).each {|i| i.push("a")}    
=> [["a", "a"], ["a", "a"]]

这不是我所期望的.但是以下构造函数样式确实符合我的预期:

Which is not what I would expect. But the following constructor style does do what I would expect:

b = Array.new(2) {Array.new}.each {|i| i.push("b")}
=> [["b"], ["b"]] 

第一个例子是预期的行为吗?

Is the first example the expected behavior?

在 ruby​​-doc 中,我的 size=2 参数看起来与两个构造函数的参数类型相同.我认为如果 each 方法被传递该参数,它将以相同的方式用于两个构造函数.

In ruby-doc it looks like my size=2 argument is the same kind of argument for both constructors. I think that if the each method is getting passed that argument that it would use it the same way for both constructors.

推荐答案

这是一个常见的误解.在您的第一个示例中,您正在创建一个包含 2 个元素的数组.这两个都是指向相同数组的指针.因此,当您遍历外部数组时,您会向内部数组添加 2 个元素,然后将其反映在输出中两次

This is a common misunderstanding. In your first example you are creating an array with 2 elements. Both of those are a pointer to the same array. So, when you iterate through your outer array you add 2 elements to the inner array, which is then reflected in your output twice

比较这些:

> array = Array.new(5, [])
=> [[], [], [], [], []] 

# Note - 5 identical object IDs (memory locations)
> array.map { |o| o.object_id }
=> [70228709214620, 70228709214620, 70228709214620, 70228709214620, 70228709214620] 

> array = Array.new(5) { [] }
=> [[], [], [], [], []] 

# Note - 5 different object IDs (memory locations)
> array.map { |o| o.object_id }
=> [70228709185900, 70228709185880, 70228709185860, 70228709185840, 70228709185780] 

这篇关于为什么 array.each 行为取决于 Array.new 语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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