str_pad
-
Instead of padding text, Ruby arrives at a similar goal by
justifyingtext to the left or right. We can left justify (STR_PAD_RIGHT) text using Ruby’sString#ljustmethod. Just like PHP’sstr_padfunction, we can specify the final string length along with the character we are using to pad.PHP
$result = str_pad("Hello", 10); var_export($result); // => 'Hello ' $result = str_pad("Hello", 10, '-'); var_export($result); // => 'Hello-----'
Ruby
p "Hello".ljust(10) # => "Hello " p "Hello".ljust(10, '-') # => "Hello-----"
We can right justify (
STR_PAD_LEFT) text using a similar approach with Ruby’sString#rjustmethod.PHP
$result = str_pad("Hello", 10, ' ', STR_PAD_LEFT); var_export($result); // => ' Hello'
Ruby
p "Hello".rjust(10) # => " Hello"
Padding on both sides (
STR_PAD_BOTH) would require us to use bothString#rjustandString#ljustin combination.PHP
$result = str_pad("Hello", 10, ' ', STR_PAD_BOTH); var_export($result); // => ' Hello '
Ruby
p "Hello".rjust(7).ljust(10) # => " Hello "
Looking for Rails or PHP web application development, integration, and training?
Rails for PHP is brought to you by Maintainable Software. Get custom web applications and personalized training from the authors of the book and website.

