Мариян обнови решението на 23.10.2016 00:06 (преди около 8 години)
+class Hash
+ def fetch_deep(path_in_hash)
+ path_in_array = path_in_hash.split('.')
+ fetch_deep_recursion(path_in_array, self)
+ end
+
+ def reshape(shape)
+ shaped(shape, self)
+ replace(shape)
+ end
+end
+class Array
+ def reshape(shape)
+ each { |item| item.reshape(shape.dup) }
+ end
+end
+ def shaped(shape, current_hash)
+ shape.keys.each do |key|
+ shaped(shape[key], current_hash) if shape[key].is_a?(Hash)
+ if shape[key].is_a?(String)
+ shape[key] = current_hash.fetch_deep(shape[key])
+ end
+ end
+ end
+
+def fetch_deep_recursion(path, hash)
+ return hash if path.empty? || hash.nil?
+ hash = convert_array_to_h(hash) if hash.is_a?(Array)
+ hash = hash.select { |key| key.to_s == path.first || key.is_a?(Array) }
+ matched_key = hash.keys.first
+ path.delete_at(0)
+ fetch_deep_recursion(path, hash[matched_key])
+end
+
+ def convert_array_to_h(hash)
+ hash.map.with_index do |item, index|
+ [index, item]
+ end.to_h
+ end