Commit c845798b authored by Yukihiro "Matz" Matsumoto's avatar Yukihiro "Matz" Matsumoto

Merge pull request #1625 from iij/pr-string-partition

add String#partition and String#rpartition.
parents 70d6d04c 120a02c1
...@@ -49,4 +49,26 @@ class String ...@@ -49,4 +49,26 @@ class String
def casecmp(str) def casecmp(str)
self.downcase <=> str.downcase self.downcase <=> str.downcase
end end
def partition(sep)
raise TypeError, "type mismatch: #{sep.class} given" unless sep.is_a? String
n = index(sep)
unless n.nil?
m = n + sep.size
[ slice(0, n), sep, slice(m, size - m) ]
else
[ self, "", "" ]
end
end
def rpartition(sep)
raise TypeError, "type mismatch: #{sep.class} given" unless sep.is_a? String
n = rindex(sep)
unless n.nil?
m = n + sep.size
[ slice(0, n), sep, slice(m, size - m) ]
else
[ "", "", self ]
end
end
end end
...@@ -114,3 +114,23 @@ assert('String#end_with?') do ...@@ -114,3 +114,23 @@ assert('String#end_with?') do
assert_true !"ng".end_with?("ing", "mng") assert_true !"ng".end_with?("ing", "mng")
assert_raise TypeError do "hello".end_with?(true) end assert_raise TypeError do "hello".end_with?(true) end
end end
assert('String#partition') do
assert_equal ["a", "x", "axa"], "axaxa".partition("x")
assert_equal ["aaaaa", "", ""], "aaaaa".partition("x")
assert_equal ["", "", "aaaaa"], "aaaaa".partition("")
assert_equal ["", "a", "aaaa"], "aaaaa".partition("a")
assert_equal ["aaaa", "b", ""], "aaaab".partition("b")
assert_equal ["", "b", "aaaa"], "baaaa".partition("b")
assert_equal ["", "", ""], "".partition("a")
end
assert('String#rpartition') do
assert_equal ["axa", "x", "a"], "axaxa".rpartition("x")
assert_equal ["", "", "aaaaa"], "aaaaa".rpartition("x")
assert_equal ["aaaaa", "", ""], "aaaaa".rpartition("")
assert_equal ["aaaa", "a", ""], "aaaaa".rpartition("a")
assert_equal ["aaaa", "b", ""], "aaaab".rpartition("b")
assert_equal ["", "b", "aaaa"], "baaaa".rpartition("b")
assert_equal ["", "", ""], "".rpartition("a")
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment