Feature #3675: String#prepend, String#>>
http://redmine.ruby-lang.org/issues/show/3675
e$B5/I<<Te(B: Sora H.
e$B%9%F!<%?%9e(B: Open, e$BM%@hEYe(B: Normal
sorahe$B$G$9e(B.
e$BDL>oe(B, Stringe$B$G$NJ8;zNs$r<jA0$KGK2uE*$K2C$($k$N$Oe(B, a = “foo”
- a e$BEy$G9T$$$^$9$,e(B,
e$BD>46$GFI$_$K$/$/e(B, e$B5-9f$J$I$G=q$-$K$/$/$J$C$F$$$k$H;W$$$^$9e(B.
e$B$J$N$Ge(B, String#prepende$B$He(B String#>>
e$B$rDI2C$9$k$H$$$&$N$O$I$&$G$7$g$&$+e(B.
e$B$=$l$>$l0J2<$N$h$&$K5!G=$7$^$9e(B.
a = “bar”
a.prepend(“foo”) #=> “foobar”
p a #=> “foobar”
b = “bar”
“foo” >> b #=> “foobar”
p b #=> “foobar”
patche$B$O$3$A$i$G$9e(B (git diff --no-prefixe$B$K$F@[email protected](B):
diff --git string.c string.c
index 0aa2e6c…6c9be57 100644
— string.c
+++ string.c
@@ -2055,6 +2055,43 @@ rb_str_concat(VALUE str1, VALUE str2)
}
}
+/*
-
- call-seq:
-
-
str.prepend(other_str) -> str
-
-
-
- Prepend—Prepend the given string to str.
-
-
- a = “world”
-
- a.prepend("hello ") #=> “hello world”
-
- a #=> “hello world”
- */
+static VALUE
+rb_str_prepend(VALUE str, VALUE str2)
+{
- StringValue(str2);
- StringValue(str);
- rb_str_update(str, 0L, 0L, str2);
- return str;
+}
+/*
-
- call-seq:
-
-
str >> other_str -> other_str
-
-
-
- Prepend—Prepend self string to other_str.
-
-
- a = “world”
-
- "hello " >> a #=> “hello world”
-
- a #=> “hello world”
- */
+static VALUE
+rb_str_prepend_to_another(VALUE str1, VALUE str2)
+{
- return rb_str_prepend(str2, str1);
+}
st_index_t
rb_memhash(const void *ptr, long len)
{
@@ -7524,6 +7561,8 @@ Init_String(void)
rb_define_method(rb_cString, “reverse!”, rb_str_reverse_bang, 0);
rb_define_method(rb_cString, “concat”, rb_str_concat, 1);
rb_define_method(rb_cString, “<<”, rb_str_concat, 1);
- rb_define_method(rb_cString, “prepend”, rb_str_prepend, 1);
- rb_define_method(rb_cString, “>>”, rb_str_prepend_to_another, 1);
rb_define_method(rb_cString, “crypt”, rb_str_crypt, 1);
rb_define_method(rb_cString, “intern”, rb_str_intern, 0);
rb_define_method(rb_cString, “to_sym”, rb_str_intern, 0);
diff --git test/ruby/test_string.rb test/ruby/test_string.rb
index 02271ce…da2477f 100644
— test/ruby/test_string.rb
+++ test/ruby/test_string.rb
@@ -1882,4 +1882,36 @@ class TestString < Test::Unit::TestCase
assert_equal(‘“\u3042\u3044\u3046”’,
“\u3042\u3044\u3046”.encode(e).inspect)
end
end - def test_prepend_to_another
- assert_equal(S(“hello world”), "hello " >> “world”)
- foo = Object.new
- def foo.to_str
-
"b"
- end
- assert_equal(S(“ab”), “a” >> foo)
- a = S(“world!”)
- b = S("hello ")
- b >> a
- assert_equal(S(“hello world!”), a)
- assert_equal(S("hello "), b)
- end
- def test_prepend
- assert_equal(S(“hello world!”), “world!”.prepend("hello "))
- foo = Object.new
- def foo.to_str
-
"b"
- end
- assert_equal(S(“ba”), “a”.prepend(foo))
- a = S(“world”)
- b = S("hello ")
- a.prepend(b)
- assert_equal(S(“hello world”), a)
- assert_equal(S("hello "), b)
- end
end