PHP to Ruby
Convert PHP code into Ruby!
-
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]
One response to “array_merge”
-
When you’re merging arrays with different keys you can also use “+” in PHP:
$user = $user_details + $account_details;
Leave a reply
-


