From 1b606025ed1a9813267bf8ac4440fc9dd5fc120c Mon Sep 17 00:00:00 2001 From: takahashim Date: Mon, 12 Jan 2015 22:16:29 +0900 Subject: add String#ljust into mruby-string-ext --- mrbgems/mruby-string-ext/mrblib/string.rb | 23 +++++++++++++++++++++++ mrbgems/mruby-string-ext/test/string.rb | 7 +++++++ 2 files changed, 30 insertions(+) diff --git a/mrbgems/mruby-string-ext/mrblib/string.rb b/mrbgems/mruby-string-ext/mrblib/string.rb index 88bdd9090..fd805b144 100644 --- a/mrbgems/mruby-string-ext/mrblib/string.rb +++ b/mrbgems/mruby-string-ext/mrblib/string.rb @@ -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 integer is greater than the length of str, returns a new + # String of length integer with str left justified + # and padded with padstr; otherwise, returns str. + # + # "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 diff --git a/mrbgems/mruby-string-ext/test/string.rb b/mrbgems/mruby-string-ext/test/string.rb index 9fa835249..83e69859b 100644 --- a/mrbgems/mruby-string-ext/test/string.rb +++ b/mrbgems/mruby-string-ext/test/string.rb @@ -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 -- cgit v1.2.3