学习 Ruby:通过块滥用创建无限维数组
有人告诉我这里发生了什么:
a = [0,1,2]
a.each {|x| a[x] = a}
结果是[[...], [...], [...]]
。如果我评估a[0]
,我会得到[[...], [...], [...]]
。如果我评估 a[0][0]
我会无限地得到 [[...], [...], [...]]
。
我是否创建了一个无限维的数组?这应该如何/为什么可行?
Somebody tell me what's going on here:
a = [0,1,2]
a.each {|x| a[x] = a}
The result is [[...], [...], [...]]
. And if I evaluate a[0]
I get [[...], [...], [...]]
. And if I evaluate a[0][0]
I get [[...], [...], [...]]
ad infinitum.
Have I created an array of infinite dimensionality? How/Why should this possibly work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上,您已经修改了
a
中的每个元素以引用列表本身。该列表递归地引用自身:(# =>
是“此行求值为”的 Rubyism),具体取决于您如何看待它,它不是无限的。它或多或少就像一张纸,两面都写着“请翻过来”的字样。
Ruby 打印
[...]
的原因是它足够聪明,可以发现列表是递归的,并避免陷入无限循环。顺便说一句,您对
each
的使用有点不惯用。each
返回列表,并且您通常不会将此返回值分配给变量(因为您已经有一个引用它的变量,在本例中为a
)。换句话说,您的代码将[0,1,2]
分配给a
,然后循环a
(将每个元素设置为a
),然后将a
分配给a
。Basically you've modified every element in
a
to reference the list itself. The list is recursively referencing itself:(
# =>
is a Rubyism for "this line evaluates to")Depending on how you look at it it is not infinite. It's more or less just like a piece of paper with the words "please turn over" written on both sides.
The reason that Ruby prints
[...]
is that it is clever enough to discover that the list is recursive, and avoids going into an infinite loop.By the way, your usage of
each
is a bit non-idiomatic.each
returns the list, and you usually don't assign this return value to a variable (since you already have a variable referencing it,a
in this case). In other words, your code assigns[0,1,2]
toa
, then loops overa
(setting each element toa
), then assignsa
toa
.我认为这是一个自引用的数据结构。 a[x]=a 将 a 的指针放入 a[x] 中。
I think it's a self-referential data structure. The a[x]=a puts a's pointer in a[x].