ko1 / rubyhackchallenge

475 stars 83 forks source link

String#join を実装する #17

Closed sankichi92 closed 6 years ago

sankichi92 commented 7 years ago

昨日の課題の延長でできそうなので python みたいな String#join を実装してみます。

','.join([1, 2]) #=> "1, 2"

ただ,python の join の方がいいと思っているわけでもないので,やっているうちに別の課題思いついたらそちらやります。

sankichi92 commented 7 years ago

とりあえず動く。

diff --git a/string.c b/string.c
index 756a60f0ac..d427d23666 100644
--- a/string.c
+++ b/string.c
@@ -10397,6 +10397,12 @@ rb_to_symbol(VALUE name)
     return rb_str_intern(name);
 }

+static VALUE
+rb_str_join(VALUE self, VALUE ary)
+{
+    return rb_ary_join(ary, self);
+}
+
 /*
  *  A <code>String</code> object holds and manipulates an arbitrary sequence of
  *  bytes, typically representing characters. String objects may be created
@@ -10562,6 +10568,8 @@ Init_String(void)
     rb_define_method(rb_cString, "valid_encoding?", rb_str_valid_encoding_p, 0);
     rb_define_method(rb_cString, "ascii_only?", rb_str_is_ascii_only_p, 0);

+    rb_define_method(rb_cString, "join", rb_str_join, 1);
+
     /* define UnicodeNormalize module here so that we don't have to look it up */
     mUnicodeNormalize          = rb_define_module("UnicodeNormalize");
     id_normalize               = rb_intern("normalize");

rb_ary_join(VALUE ary, VALUE sep) の実装読んでみます。