-
array_merge
Posted on October 19th, 2010 1 commentThe array_merge() function in PHP merges 2 arrays by appending the second array onto the first array, and returning the resulting array.
The way to do this in Ruby depends on the type of data - if dealing with associative arrays (known as a hash in Ruby), we can use the merge() method of the Ruby Hash class.
PHP
$user_details = array('name' => 'John', 'age' => 20); $account_details = array('credits' => '50', 'id' => 4); $user = array_merge($user_details, $account_details); print_r($user); /* Array ( [name] => John [age] => 20 [credits] => 50 [id] => 4 ) */
Ruby
user_details = { :name => 'John', :age => 20 } account_details = { :credits => 50, :id => 4 } p user_details.merge(account_details); # => {:credits=>50, :name=>"John", :id=>4, :age=>20}
Merging numeric arrays in Ruby is much easier as shown below (PHP example given first).
PHP
$start = array(1, 2, 3); $finish = array(4, 5, 6); $nums = array_merge($start, $finish); print_r($nums); /* Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 ) */
Ruby
start = [1, 2, 3]; finish = [4, 5, 6]; nums = start + finish; p nums; # => [1, 2, 3, 4, 5, 6]
-
array_fill
Posted on October 13th, 2010 1 commentThe 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']


