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

    Posted on October 13th, 2010 RubyLove 1 comment

    The array_fill() function in PHP allows an array to be populated (i.e. filled) with a particular value.

    PHP

    $a = array_fill(3, 5, 'php');
    print_r($a);
    /*
    Array (
    	[3] => php
    	[4] => php
    	[5] => php
    	[6] => php
    	[7] => php
    )
    */

    In Ruby this is not really possible because Ruby arrays must have their keys filled in the correct order, i.e. you cant skip assigning values to keys in a Ruby array. As such, the next best thing is to fill those values with nil, or use a hash instead.

    Ruby

    a = [nil] * 3 + ['php'] * 5;
    puts a;
    # => [nil, nil, nil, 'php', 'php', 'php', 'php', 'php']
     

    One response to “array_fill”

    1. With a hash

      a = {}
      5.times{|i| a[i+3] = ‘php’}
      puts a
      # => {3=>”php”, 4=>”php”, 5=>”php”, 6=>”php”, 7=>”php”}

    Leave a reply