substr

  • Retrieving part of a string by a specified position is done in Ruby using String#[] or it’s synonym method String#slice.

    Return the first five characters of a string:

    PHP

    print substr("hello world", 0, 5);
    // hello

    Ruby

    puts "hello world".slice(0, 5)
    puts "hello world"[0, 5]
    # hello

    Return all characters after a specified position. In Ruby we can use Ranges to specify a range of character positions:

    PHP

    print substr("hello world", 3);
    // lo world

    Ruby

    puts "hello world".slice(3..-1)
    puts "hello world"[3..-1]
    # lo world

    Return the last five characters in the string:

    PHP

    print substr("hello world", -5);
    // world

    Ruby

    puts "hello world"[-5, 5]
    puts "hello world".slice(-5, 5)
    # world

    see also

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.