PHP to Ruby
Convert PHP code into Ruby!
-
array_fill_keys
Posted on November 11th, 2010 1 commentThe 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”
-
Why the bleep is this so complicated?
Try this:result = {}
keys.each{|k| result[k] = ‘code’}
Leave a reply
-


