Skip to content

Commit 5cb0c74

Browse files
committed
array.c (mrb_ary_to_s): add recursive check to Array#inspect
1 parent e2bbf75 commit 5cb0c74

File tree

2 files changed

+30
-21
lines changed

2 files changed

+30
-21
lines changed

mrblib/array.rb

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -101,27 +101,6 @@ def initialize(size=0, obj=nil, &block)
101101
self
102102
end
103103

104-
def _inspect(recur_list)
105-
size = self.size
106-
return "[]" if size == 0
107-
return "[...]" if recur_list[self.object_id]
108-
recur_list[self.object_id] = true
109-
ary=[]
110-
i=0
111-
while i<size
112-
ary<<self[i]._inspect(recur_list)
113-
i+=1
114-
end
115-
"["+ary.join(", ")+"]"
116-
end
117-
##
118-
# Return the contents of this array as a string.
119-
#
120-
def inspect
121-
self._inspect({})
122-
end
123-
alias to_s inspect
124-
125104
##
126105
# call-seq:
127106
# array == other -> true or false

src/array.c

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1331,6 +1331,34 @@ mrb_ary_join_m(mrb_state *mrb, mrb_value ary)
13311331
return mrb_ary_join(mrb, ary, sep);
13321332
}
13331333

1334+
/*
1335+
* call-seq:
1336+
* ary.to_s -> string
1337+
* ary.inspect -> string
1338+
*
1339+
* Return the contents of this array as a string.
1340+
*/
1341+
static mrb_value
1342+
mrb_ary_to_s(mrb_state *mrb, mrb_value self)
1343+
{
1344+
mrb->c->ci->mid = MRB_SYM(inspect);
1345+
mrb_value ret = mrb_str_new_lit(mrb, "[");
1346+
int ai = mrb_gc_arena_save(mrb);
1347+
if (mrb_inspect_recursive_p(mrb, self)) {
1348+
mrb_str_cat_lit(mrb, ret, "...]");
1349+
return ret;
1350+
}
1351+
mrb_int len = RARRAY_LEN(self);
1352+
for (mrb_int i=0; i<len; i++) {
1353+
if (i>0) mrb_str_cat_lit(mrb, ret, ", ");
1354+
mrb_str_cat_str(mrb, ret, mrb_inspect(mrb, mrb_ary_ref(mrb, self, i)));
1355+
mrb_gc_arena_restore(mrb, ai);
1356+
}
1357+
mrb_str_cat_lit(mrb, ret, "]");
1358+
1359+
return ret;
1360+
}
1361+
13341362
static mrb_value
13351363
mrb_ary_eq(mrb_state *mrb, mrb_value ary1)
13361364
{
@@ -1409,6 +1437,8 @@ mrb_init_array(mrb_state *mrb)
14091437
mrb_define_method(mrb, a, "size", mrb_ary_size, MRB_ARGS_NONE()); /* 15.2.12.5.28 */
14101438
mrb_define_method(mrb, a, "slice", mrb_ary_aget, MRB_ARGS_ARG(1,1)); /* 15.2.12.5.29 */
14111439
mrb_define_method(mrb, a, "unshift", mrb_ary_unshift_m, MRB_ARGS_ANY()); /* 15.2.12.5.30 */
1440+
mrb_define_method(mrb, a, "to_s", mrb_ary_to_s, MRB_ARGS_NONE());
1441+
mrb_define_method(mrb, a, "inspect", mrb_ary_to_s, MRB_ARGS_NONE());
14121442

14131443
mrb_define_method(mrb, a, "__ary_eq", mrb_ary_eq, MRB_ARGS_REQ(1));
14141444
mrb_define_method(mrb, a, "__ary_cmp", mrb_ary_cmp, MRB_ARGS_REQ(1));

0 commit comments

Comments
 (0)