Добрин обнови решението на 21.10.2016 20:06 (преди около 8 години)
+def put_in_result(result, current_key)
+ if result.is_a? Array
+ result[current_key.to_i]
+ elsif result.is_a? Hash
+ result[current_key] || result[current_key.to_sym]
+ else
+ nil
+ end
+end
+
+class Hash
+ def fetch_deep(path)
+ keys = path.split('.')
+ return nil if keys.empty?
+ return nil unless result = self[keys[0]] || self[keys[0].to_sym]
+ keys[1..-1].each do |current_key|
+ result = put_in_result(result, current_key)
+ end
+ result
+ end
+
+ def reshape(shape)
+ self_copy = self.dup
+ self.clear
+ shape.each do |key, path|
+ hash_take_value_or_use_recursion(key, path, self, self_copy)
+ end
+ self
+ end
+end
+
+def hash_take_value_or_use_recursion(key, path, current_hash, hash_old_version)
+ if path.is_a? String
+ current_hash[key] = hash_old_version.fetch_deep(path)
+ elsif path.is_a? Hash
+ current_hash[key] = hash_old_version
+ current_hash[key].reshape(path)
+ end
+end
+
+class Array
+ def reshape(shape)
+ self.each { |hash_element| hash_element.reshape(shape) }
+ end
+end