-
array_combine
Posted on July 23rd, 2009 2 commentsThe array_combine() function creates an associative array (hash) by using one array for keys and another for values.
PHP
$a = array('python', 'lisp', 'perl'); $b = array('PY', 'LI', 'PE'); $c = array_combine($a, $b); print_r($c); => /* Array ( [python] => PY [lisp] => LI [perl] => PE ) */
To replicate this functionality in Ruby, we need to use a Hash object, since arrays in Ruby don’t use associative key/value pairs.
Since there is no exact equivalent of to the array_combine() function in Ruby, we manually create a hash from two different arrays.
Ruby
p1 = ['python', 'lisp', 'perl']; p2 = ['PY', 'LI', 'PE']; # initialize the hash combined_hash = {} # build the hash from 2 different arrays p2.each_with_index do |val, key| combined_hash[p1[key]] = val end # print resulting hash p combined_hash => # ["python"=>"PY", "lisp"=>"LI", "perl"=>"PE"]
2 responses to “array_combine”
-
I think this will look much better:
p1 = ['python', 'lisp', 'perl'];
p2 = ['PY', 'LI', 'PE'];[p1,p2].transpose.inject({}) {|res,pair| res.merge({pair[0] => pair[1] }) }
=> # {”python”=>”PY”, “perl”=>”PE”, “lisp”=>”LI”}
-
And even easier!
p1 = ['python', 'lisp', 'perl'];
p2 = ['PY', 'LI', 'PE'];
Hash[*[p1,p2].transpose.flatten]=> # {”python”=>”PY”, “perl”=>”PE”, “lisp”=>”LI”}
Leave a reply
-


