Радослав обнови решението на 24.10.2016 00:58 (преди около 8 години)
+class Hash
+ def fetch_deep(key_path)
+ path_split = key_path.split('.')
+ current_key = path_split.shift
+ symbol_key_result = get_result(self[current_key.to_sym], path_split)
+ string_key_result = get_result(self[current_key], path_split)
+ symbol_key_result != nil ? symbol_key_result : string_key_result
+ end
+
+ def reshape(new_shape)
+ buffer_shape = Marshal.load( Marshal.dump(new_shape) )
+ shapeshifter(self, buffer_shape)
+ self.replace(buffer_shape)
+ end
+
+ private
+
+ def array_handler(current_object, path_split)
+ if current_object[to_number_convert(path_split[0])]
+ get_result(current_object[path_split.shift.to_i], path_split)
+ end
+ end
+
+ def to_number_convert(string)
+ num = string.to_i
+ if num.to_s == string
+ num
+ else
+ 999_999
+ end
+ end
+
+ def get_result(current_object, path_split)
+ if path_split.empty?
+ current_object
+ elsif current_object.is_a? Array
+ array_handler(current_object, path_split)
+ elsif !current_object.is_a?Hash
+ else
+ current_object.fetch_deep(path_split.join('.'))
+ end
+ end
+
+ def shapeshifter(old_shape, buffer_shape)
+ buffer_shape.map do |x, y|
+ if buffer_shape[x].is_a? Hash
+ shapeshifter(old_shape, buffer_shape[x])
+ else
+ buffer_shape[x] = old_shape.fetch_deep(y)
+ end
+ end
+ end
+end
+class Array
+ def reshape(new_shape)
+ self.map! { |x| x.reshape(new_shape) }
+ end
+end