红宝石阵奇怪的事情(无限阵列) [英] ruby array strange thing (infinite array)

查看:186
本文介绍了红宝石阵奇怪的事情(无限阵列)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我写了下面的code:

When i write the following code:

x= [1,2,3]
x << x
puts x
puts x[3]
puts x[3][3][3][3][3][3][3][3][3][3]

我得到这样的输出:

I get this output:

[1, 2, 3, [...]]
[1, 2, 3, [...]]
[1, 2, 3, [...]]

我不应该只得到[1,2,3,[1,2,3],什么会是如何解释呢?

Shouldn't I get only [1,2,3,[1,2,3]] and what would be the explanation?

推荐答案

有什么奇怪的这件事。数组的第四个要素是数组本身,所以当你问第四个元素,你得到的数组,当你问的第四个元素的第四个元素,你得到的数组,当你问第四第四个元素的第四个元素的第四个元素的元素......你得到的数组。

There's nothing strange about this. The fourth element of the array is the array itself, so when you ask for the fourth element, you get the array, and when you ask for the fourth element of the fourth element, you get the array, and when you ask for the fourth element of the fourth element of the fourth element of the fourth element ... you get the array.

就这么简单。

唯一有点不同寻常的是,阵列#to_s 检测到这样的递归和,而不是进入一个无限循环,返回一个省略号。

The only slightly unusual thing is that Array#to_s detects such recursion and instead of going into an infinite loop, returns an ellipsis.

这篇关于红宝石阵奇怪的事情(无限阵列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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