Convert PHP code into Ruby!
RSS icon Email icon Home icon
  • str_pad

    Posted on May 23rd, 2009 RubyLove No comments

    str_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**'