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

    Posted on June 13th, 2009 RubyLove No comments

    The 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'

    Leave a reply