Милена обнови решението на 23.10.2016 14:06 (преди около 8 години)
+class Hash
+ def fetch_deep(path)
+ fetch_recursion(keys_to_s, path.split('.'))
+ end
+
+ def keys_to_s
+ result = {}
+ map do |key, value|
+ result[key.to_s] = value.is_a?(Hash) ? value.keys_to_s : value
+ if value.is_a?(Array)
+ result[key.to_s] = value.collect { |v| v.keys_to_s if v.is_a?(Hash) }
+ end
+ end
+ result
+ end
+
+ def fetch_recursion(hash, path)
+ return hash.fetch(path.first) if path.size == 1
+ return fetch_recursion(hash[path.shift.to_i], path) if hash.is_a?(Array)
+ fetch_recursion(hash.fetch(path.shift), path)
+ end
+
+ def reshape(shape)
+ reshape_recursion(shape, {})
+ end
+
+ def reshape_recursion(shape, self_copy)
+ shape.each do |key, value|
+ self_copy[key] = if value.is_a?(Hash)
+ reshape_recursion(value, {})
+ else
+ fetch_deep(value)
+ end
+ end
+ self_copy
+ end
+end
+
+class Array
+ def reshape(shape)
+ array = []
+ each { |h| array << h.to_h.reshape(shape) }
+ array
+ end
+end