summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-string-ext/mrblib/string.rb
diff options
context:
space:
mode:
authorTomasz Dabrowski <[email protected]>2017-02-10 15:17:20 +0100
committerTomasz Dabrowski <[email protected]>2017-02-10 15:31:33 +0100
commitac9d04f4af6e229ad8e0f306c745b07b404978f5 (patch)
tree08c173c0e5fdb9da03b53e9e5a6be7436799aec3 /mrbgems/mruby-string-ext/mrblib/string.rb
parent24048cd998777757147b14948e0a149dffcac76d (diff)
downloadmruby-ac9d04f4af6e229ad8e0f306c745b07b404978f5.tar.gz
mruby-ac9d04f4af6e229ad8e0f306c745b07b404978f5.zip
String#ljust and String#rjust reimplemented with optimized Ruby
Diffstat (limited to 'mrbgems/mruby-string-ext/mrblib/string.rb')
-rw-r--r--mrbgems/mruby-string-ext/mrblib/string.rb38
1 files changed, 38 insertions, 0 deletions
diff --git a/mrbgems/mruby-string-ext/mrblib/string.rb b/mrbgems/mruby-string-ext/mrblib/string.rb
index 610a462a7..8895b7ad3 100644
--- a/mrbgems/mruby-string-ext/mrblib/string.rb
+++ b/mrbgems/mruby-string-ext/mrblib/string.rb
@@ -263,6 +263,44 @@ class String
self
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 = ' ')
+ raise ArgumentError, 'zero width padding' if padstr == ''
+ return self if idx <= self.size
+ pad_repetitions = (idx / padstr.length).ceil
+ padding = (padstr * pad_repetitions)[0...(idx - self.length)]
+ self + padding
+ end
+
+ ##
+ # call-seq:
+ # str.rjust(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> right justified
+ # and padded with <i>padstr</i>; otherwise, returns <i>str</i>.
+ #
+ # "hello".rjust(4) #=> "hello"
+ # "hello".rjust(20) #=> " hello"
+ # "hello".rjust(20, '1234') #=> "123412341234123hello"
+ def rjust(idx, padstr = ' ')
+ raise ArgumentError, 'zero width padding' if padstr == ''
+ return self if idx <= self.size
+ pad_repetitions = (idx / padstr.length).ceil
+ padding = (padstr * pad_repetitions)[0...(idx - self.length)]
+ padding + self
+ end
+
# str.upto(other_str, exclusive=false) {|s| block } -> str
# str.upto(other_str, exclusive=false) -> an_enumerator
#