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

    Posted on October 1st, 2009 RubyLove No comments

    The list() function in PHP is used to assign multiple variables as if they were an array. Technically, list() is not a function in PHP, it is a language construct.

    Ruby has no real need for a function such as list(), as the same can be achieve using parallel assignment - i.e. assigning comma separated variables to elements of an array using the normal assignment operator.

    PHP

    $langs = array('php', 'ruby', 'perl');
    list($lang1, $lang2, $lang3) = $langs;
    echo $lang1;	// php
    echo $lang2;	// ruby
    echo $lang3;	// perl

    Ruby

    langs = [ "php", "ruby", "perl" ];
    lang1, lang2, lang3 = langs;
    puts lang1;	# php
    puts lang2;	# ruby
    puts lang3;	# perl
  • implode

    Posted on June 1st, 2009 RubyLove No comments

    The implode function takes and array and forms a string by concatenating the elements in the array.

    PHP

    $langs = array('python', 'java', 'ruby');
    $string = implode(', ', $langs);
    echo $string;
    // => python, java, ruby

    Ruby

    puts ['perl', 'python', 'java'].join(', ');
    # => python, java, ruby
  • explode

    Posted on May 29th, 2009 RubyLove No comments

    The explode function takes 2 parameters - the first is the delimiter, and the second is the string to be exploded. It returns an array of strings, each of which is a substring of the original, formed by splitting the original string on boundaries formed by the string delimiter.

    PHP

    $my_string = 'perl, python, java';
    $array = explode(', ', $my_string);
    var_dump($a);
    /*
    Array (
    	[0] => perl
    	[1] => python
    	[2] => java
    )
    */

    Ruby

    my_string = 'perl, python, java';
    puts my_string.split(', ');
    # => ["perl", "python", "java"]