mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
Merge pull request #2700 from takahashim/string-ljust
add String#ljust into mruby-string-ext
This commit is contained in:
@@ -244,4 +244,27 @@ class String
|
||||
return str + self if pos == 0
|
||||
return self[0..pos - 1] + str + self[pos..-1]
|
||||
end
|
||||
|
||||
##
|
||||
# call-seq:
|
||||
# str.ljust(integer, padstr=' ') -> new_str
|
||||
#
|
||||
# If <i>integer</i> is greater than the length of <i>str</i>, returns a new
|
||||
# <code>String</code> of length <i>integer</i> with <i>str</i> left justified
|
||||
# and padded with <i>padstr</i>; otherwise, returns <i>str</i>.
|
||||
#
|
||||
# "hello".ljust(4) #=> "hello"
|
||||
# "hello".ljust(20) #=> "hello "
|
||||
# "hello".ljust(20, '1234') #=> "hello123412341234123"
|
||||
def ljust(idx, padstr = ' ')
|
||||
if idx <= self.size
|
||||
return self
|
||||
end
|
||||
newstr = self.dup
|
||||
newstr << padstr
|
||||
while newstr.size <= idx
|
||||
newstr << padstr
|
||||
end
|
||||
return newstr.slice(0,idx)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -386,3 +386,10 @@ assert('String#prepend') do
|
||||
assert_equal "hello world", a.prepend("hello ")
|
||||
assert_equal "hello world", a
|
||||
end
|
||||
|
||||
assert('String#ljust') do
|
||||
assert_equal "hello", "hello".ljust(4)
|
||||
assert_equal "hello ", "hello".ljust(20)
|
||||
assert_equal "hello123412341234123", "hello".ljust(20, '1234')
|
||||
assert_equal "hello", "hello".ljust(-3)
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user