summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-string-ext/mrblib/string.rb
diff options
context:
space:
mode:
authorYukihiro "Matz" Matsumoto <[email protected]>2017-02-11 10:26:09 +0900
committerGitHub <[email protected]>2017-02-11 10:26:09 +0900
commitb36495bcb5a4f30144bc27c38167d02907ca8dc7 (patch)
tree9a97ca0f35e20c5cc7109c16601f89c44a2a7c69 /mrbgems/mruby-string-ext/mrblib/string.rb
parentc802cd07baf7132c5053defac883f0ee6b7967b7 (diff)
parentd1bc7caecaf337976351934d5910726106601bd9 (diff)
downloadmruby-b36495bcb5a4f30144bc27c38167d02907ca8dc7.tar.gz
mruby-b36495bcb5a4f30144bc27c38167d02907ca8dc7.zip
Merge pull request #3449 from dabroz/fix-ljust-ruby
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
#