学习 Ruby:通过块滥用创建无限维数组

发布于 2024-10-12 07:50:42 字数 296 浏览 3 评论 0原文

有人告诉我这里发生了什么:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

遇见了你 2024-10-19 07:50:42

基本上,您已经修改了 a 中的每个元素以引用列表本身。该列表递归地引用自身:(

a[0] # => a
a[0][0] # => a[0], which is a
a[0][0][0] # => a[0][0], which is a[0], which is 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:

a[0] # => a
a[0][0] # => a[0], which is a
a[0][0][0] # => a[0][0], which is a[0], which is a
...

(# => 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] to a, then loops over a (setting each element to a), then assigns a to a.

メ斷腸人バ 2024-10-19 07:50:42

我认为这是一个自引用的数据结构。 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].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文