Replace recursive()

Jmnote (토론 | 기여)님의 2016년 2월 1일 (월) 15:18 판 (→‎Ruby)
associative array replace recursive
replace_recursive()

1 PHP

$computer1 = array(
	'owner' => 'John',
	'softwares' => array( 'Windows', 'Office', 'Photoshop', 'Python', 'Apache' ),
	'peripherals' => array( 'keyboard' => 'Samsung' ),
);

$computer2 = array(
	'owner' => 'Jane',
	'softwares' => array( 'Linux', 'Apache', 'MySQL', 'PHP' ),
	'peripherals' => array( 'keyboard' => 'LG', 'mouse' => 'LG' ),
);

$merged1 = array_replace_recursive($computer1, $computer2);
$merged2 = array_replace_recursive($computer2, $computer1);

print_r( $merged1 );
# Array
# (
#     [owner] => Jane
#     [softwares] => Array
#         (
#             [0] => Linux
#             [1] => Apache
#             [2] => MySQL
#             [3] => PHP
#             [4] => Apache
#         )
# 
#     [peripherals] => Array
#         (
#             [keyboard] => LG
#             [mouse] => LG
#         )
# 
# )

print_r( $merged2 );
# Array
# (
#     [owner] => John
#     [softwares] => Array
#         (
#             [0] => Windows
#             [1] => Office
#             [2] => Photoshop
#             [3] => Python
#             [4] => Apache
#         )
# 
#     [peripherals] => Array
#         (
#             [keyboard] => Samsung
#             [mouser] => LG
#         )
# 
# )

2 Ruby

def replace_recursive(base, replacements)
	def replace_recursive_array(base, replacements)
		replacements.each_with_index do | v, i |
			if( v.kind_of?(Array) )
				base[i] = replace_recursive_array(base[i], v)
			elsif( v.kind_of?(Hash) )
				base[i] = replace_recursive_hash(base[i], v)
			else 
				base[i] = v
			end
		end
		base
	end
	
	def replace_recursive_hash(base, replacements)
		replacements.each do | k, v |
			if( v.kind_of?(Array) )
				base[k] = replace_recursive_array(base[k], v)
			elsif( v.kind_of?(Hash) )
				base[k] = replace_recursive_hash(base[k], v)
			else 
				base[k] = v
			end
		end
		base
	end

	base = Marshal.load(Marshal.dump(base))
	if( replacements.kind_of?(Array) )
		replace_recursive_array(base, replacements)
	elsif( replacements.kind_of?(Hash) )
		replace_recursive_hash(base, replacements)
	else 
		replacements
	end	
end

computer1 = {
	'owner' => 'John',
	'softwares' => [ 'Windows', 'Office', 'Photoshop', 'Python', 'Apache' ],
	'peripherals' => { 'keyboard' => 'Samsung' }
}

computer2 = {
	'owner' => 'Jane',
	'softwares' => [ 'Linux', 'Apache', 'MySQL', 'PHP' ],
	'peripherals' => {'keyboard' => 'LG', 'mouse' => 'LG' },
}
puts replace_recursive(computer1, computer2).inspect
# {"peripherals"=>{"mouse"=>"LG", "keyboard"=>"LG"}, "softwares"=>["Linux", "Apache", "MySQL", "PHP", "Apache"], "owner"=>"Jane"}
puts replace_recursive(computer2, computer1).inspect
# {"peripherals"=>{"mouse"=>"LG", "keyboard"=>"Samsung"}, "softwares"=>["Windows", "Office", "Photoshop", "Python", "Apache"], "owner"=>"John"}

3 같이 보기

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}