trim

  • Stripping whitespace from the beginning and end of a string is done in Ruby using the String#strip method.

    PHP

    $result = trim(" \nhello world \n");
    var_export($result);
    // => 'hello world'

    Ruby

    p " \nhello world \n".strip
    # => "hello world"

    PHP’s trim function has a second argument to specify the characters to strip. We can do this in Ruby using the String#gsub method.

    PHP

    $result = trim(" /Users/joe/work/ ", " /");
    var_export($result);
    // => 'Users/joe/work'

    Ruby

    chars = " /"
    p " /Users/joe/work/ ".gsub(/^[#{chars}]+|[#{chars}]+$/, '')
    # => "Users/joe/work"

    see also

touch ucfirst

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.