Калина обнови решението на 19.10.2016 21:19 (преди около 8 години)
+class Hash
+ def fetch_deep(path)
+ path_elements = path.split('.')
+ result = self.deep_stringify_keys
+ path_elements.reduce(result) do |hsh, key|
+ key = Integer(key) if key.number?
+ hsh[key] if hsh
+ end
+ end
+
+ def reshape(shape)
+ shape.each_with_object({}) do |(key, value), result|
+ if value.is_a? Hash
+ reshape(value)
+ else
+ result[key] = fetch_deep(value)
+ end
+ end
+ end
+
+ def deep_stringify_keys
+ deep_transform_keys(self, &:to_s)
+ end
+
+ def deep_transform_keys(object, &block)
+ if object.is_a? Hash
+ object.each_with_object({}) do |(key, value), result|
+ result[yield(key)] = deep_transform_keys(value, &block)
+ end
+ elsif object.is_a? Array
+ object.map { |e| deep_transform_keys(e, &block) }
+ else object
+ end
+ end
+end
+
+class Array
+ def reshape(shape)
+ self.map! do |hsh|
+ hsh.reshape(shape)
+ end
+ end
+end
+
+class String
+ def number?
+ true if Integer(self) rescue false
+ end
+end