-
rtrim
Posted on June 19th, 2009 No commentsThe rtrim function strips whitespace (or other characters) from the end of a string.
PHP
echo rtrim('Work Hard. Play Harder.', ' Play Harder.'); => // 'Work Hard.'
Ruby
substitute = 'Play Harder.'; puts "Work Hard. Play Harder.".gsub(/[#{substitute}]+$/, '') => # 'Work Hard.'
-
ltrim
Posted on June 16th, 2009 No commentsThe ltrim function strips whitespace (or other characters) from the beginning of a string.
PHP
echo ltrim('John and I love icecream', 'John and '); => // 'I love icecream'
Ruby
substitute = 'John and '; puts "John and I love icecream".gsub(/^[#{substitute}]+/, '') => # 'I love icecream'
-
trim
Posted on June 13th, 2009 No commentsThe trim function is mainly used to remove whitespace from the beginning and end of strings, although it can be used to remove other characters too.
PHP
echo trim(" Hello World "); => // 'Hello World'
Ruby
puts " Hello World ".strip => # 'Hello World'
The trim() function can also take a second argument which allows the removal of an arbitrary character.
PHP
echo trim("\n\nHello World\n\n", "\n"); => // 'Hello World'
Ruby
substitute = '\n'; puts "\n\nHello World\n\n".gsub(/^[#{substitute}]+|[#{substitute}]+$/, '') => # 'Hello World'
-
chr
Posted on June 10th, 2009 No commentsThe chr function returns a one-character string, which represents the character specified by an ASCII code.
PHP
echo chr(115); => // s
Ruby
puts 115.chr => # s
-
str_pad
Posted on May 23rd, 2009 No commentsstr_pad allows a string to be added to a particular length using another string.
PHP
echo str_pad('Hi', 5); // => 'Hi ' echo str_pad('Hi', 5, '+'); // => 'Hi+++' echo str_pad('78', 5, '0', STR_PAD_LEFT); // => '00078'
Instead of padding a string, in Ruby we justify a string to the left or right.
Ruby
puts "Hi".ljust(5); # => 'Hi ' puts "Hi".ljust(5, '+'); # => 'Hi+++' puts "78".rjust(5, '0'); # => '00078'
To pad both sides of a string, we need to use a combination of ljust and rjust.
PHP
echo str_pad('Special', 11, '*', STR_PAD_BOTH); // => '**Special**'
Ruby
puts "Special".ljust(9).rjust(11); # => '**Special**'
-
strtoupper
Posted on March 31st, 2009 No commentsReturns the argument provided with all alphabetic characters converted to uppercase.
PHP
echo strtoupper('Ruby is pure OO'); // => RUBY IS PURE OO
Ruby
puts 'Ruby is pure OO'.upcase; # => RUBY IS PURE OO


