Ралица обнови решението на 20.10.2016 23:41 (преди около 8 години)
+def fetch_element_in_array(current_object, key)
+ key_not_digit_characters = /[^-+\d]/.match(key)
+
+ if key_not_digit_characters == nil
+ if current_object[key.to_i] != nil
+ current_object[key.to_i]
+ else nil
+ end
+ else nil
+ end
+end
+
+def fetch_element_in_hash(current_object, key)
+ if current_object[key] != nil
+ current_object[key]
+ elsif current_object[key.to_sym] != nil
+ current_object[key.to_sym]
+ else
+ nil
+ end
+end
+
+def get_result_object(current_object, key)
+ if current_object.is_a?(Numeric)
+ nil
+ elsif current_object.is_a?(Array) || current_object.is_a?(String)
+ fetch_element_in_array(current_object, key)
+ else
+ fetch_element_in_hash(current_object, key)
+ end
+end
+
+def follow_path_of_keys(current_object, path_array)
+ path_array.each do |key|
+ current_object = get_result_object(current_object, key)
+ end
+ current_object
+end
+
+class Hash
+ def fetch_deep(path)
+
+ path_array = path.split('.')
+ current_object = self
+ current_object = follow_path_of_keys(current_object, path_array)
+ current_object
+ end
+end
+
+def follow_deep_keys_in_shape(initial_hash, shape_hash, key)
+ if shape_hash[key].is_a?(String)
+ shape_hash[key] = initial_hash.fetch_deep(shape_hash[key])
+ elsif shape_hash[key].is_a?(Numeric)
+ # shape_hash[key]
+ else
+ shape_hash[key].keys.each do |new_key|
+ follow_deep_keys_in_shape(initial_hash, shape_hash[key], new_key)
+ end
+ end
+end
+
+class Hash
+ def reshape(shape)
+ copy_shape = Marshal.load(Marshal.dump(shape))
+
+ copy_shape.keys.each do |key|
+ follow_deep_keys_in_shape(self, copy_shape, key)
+ end
+ self.replace(copy_shape)
+ end
+end
+
+class Array
+ def reshape(shape)
+ self.each do |item|
+ item.reshape(shape)
+ end
+ end
+end