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

    Posted on November 11th, 2010 RubyLove 1 comment

    The array_fill_keys() function in PHP allows you to populate the values of an array while specifying its keys.

    PHP

    $keys = array('write', 'debug', 'execute');
    $result = array_fill_keys($keys, 'code');
    var_export($result);
    // => array('write' => 'code', 'debug' => 'code', 'execute' => 'code')

    To replicate this functionality in Ruby, we need to use a Hash object, since arrays in Ruby don’t use associative key/value pairs.

    Ruby

    keys = ['write', 'debug', 'execute']
    result = keys.inject({}) do |hash, key| 
      hash[key] = 'code'
      hash 
    end
    p result
    # => {"write"=>"code", "debug"=>"code", "execute"=>"code"}
     

    One response to “array_fill_keys”

    1. Why the bleep is this so complicated?
      Try this:

      result = {}
      keys.each{|k| result[k] = ‘code’}

    Leave a reply