n=[1,2] a=n << n p n 输出:[1,2,[...]] 什么情况
p 的输出来自对象的 inspect 方法,array 的 inspect 方法如下,可以找到这个[...]
的由来
MRI/array.c
1863 static VALUE
1864 rb_ary_inspect(VALUE ary)
1865 {
1866 if (RARRAY_LEN(ary) == 0) return rb_usascii_str_new2("[]");
1867 return rb_exec_recursive(inspect_ary, ary, 0);
1868 }
1830 inspect_ary(VALUE ary, VALUE dummy, int recur)
1831 {
1832 int tainted = OBJ_TAINTED(ary);
1833 int untrust = OBJ_UNTRUSTED(ary);
1834 long i;
1835 VALUE s, str;
1836
1837 if (recur) return rb_usascii_str_new_cstr("[...]");
1838 str = rb_str_buf_new2("[");
1839 for (i=0; i<RARRAY_LEN(ary); i++) {
1840 s = rb_inspect(RARRAY_PTR(ary)[i]);
1841 if (OBJ_TAINTED(s)) tainted = TRUE;
1842 if (OBJ_UNTRUSTED(s)) untrust = TRUE;
1843 if (i > 0) rb_str_buf_cat2(str, ", ");
1844 else rb_enc_copy(str, s);
1845 rb_str_buf_append(str, s);
1846 }
1847 rb_str_buf_cat2(str, "]");
1848 if (tainted) OBJ_TAINT(str);
1849 if (untrust) OBJ_UNTRUST(str);
1850 return str;
1851 }
这是递归数组,在表示 Directed graph 的时候很直观:
http://stackoverflow.com/questions/10606734/what-are-recursive-arrays-good-for
其实还有递归哈希的:
1.9.3p194 :032 > a = {:a => 1}
=> {:a=>1}
1.9.3p194 :033 > a[:b] = a
=> {:a=>1, :b=>{...}}
1.9.3p194 :034 > a[:b]
=> {:a=>1, :b=>{...}}
1.9.3p194 :035 > a[:b][:b]
=> {:a=>1, :b=>{...}}
1.9.3p194 :036 > a[:b][:b][:b]
=> {:a=>1, :b=>{...}}
挺有趣的
1.9.3p194 :018 > a.each { |i| puts i }
1
2
1
2
[...]
=> [1, 2, [...]]
实际上,上而的语句应该是无限循环执行下去吧?