Даниела обнови решението на 24.10.2016 03:43 (преди около 8 години)
+class Hash
+ def fetch_deep(path)
+ path_array = path.split(".")
+ follow_path(path_array)
+ end
+
+ def follow_path(path_array)
+ if path_array.size == 1
+ follow_path_if_size_1(path_array)
+ else
+ follow_path_if_size_more_than_1(path_array)
+ end
+ end
+
+ def follow_path_if_size_1(path_array)
+ if self.key?(path_array[0].to_sym)
+ self[path_array[0].to_sym]
+ elsif self.key?(path_array[0])
+ self[path_array[0]]
+ end
+ end
+
+ def follow_path_if_size_more_than_1(path_array)
+ if self.key?(path_array[0].to_sym)
+ self[path_array.shift.to_sym].follow_path(path_array)
+ elsif self.key?(path_array[0])
+ self[path_array.shift].follow_path(path_array)
+ end
+ end
+
+ def reshape(shape)
+ if shape.values[0].class == Hash
+ paths = shape.values
+ shape.keys.map do |n|
+ [n, simple_reshape(paths.shift)]
+ end.to_h
+ else
+ simple_reshape(shape)
+ end
+ end
+
+ def simple_reshape(shape)
+ paths = shape.values
+ shape.keys.map do |n|
+ [n, self.fetch_deep(paths.shift)]
+ end.to_h
+ end
+end
+
+class Array
+ def follow_path(path_array)
+ if path_array.size == 1
+ self[path_array[0].to_i]
+ else
+ self[path_array.shift.to_i].follow_path(path_array)
+ end
+ end
+
+ def reshape(shape)
+ new_array = []
+ new_array << self.shift.reshape(shape) until self.empty?
+ new_array
+ end
+end
+
+class NilClass
+ def follow_path(_path_array)
+ nil
+ end
+end