Решение на Втора задача - хешове, масиви и структура от Натали Арабаджийска

Обратно към всички решения

Към профила на Натали Арабаджийска

Резултати

  • 4 точки от тестове
  • 0 бонус точки
  • 4 точки общо
  • 11 успешни тест(а)
  • 4 неуспешни тест(а)

Код

class Hash
def key_to_sym(myhash)
myhash.keys.each do |key|
myhash[(key.to_sym rescue key) || key] = myhash.delete(key)
end
myhash
end
def fetch_deep(path)
path.split('.').reduce(key_to_sym(self)) do |memo, key|
if memo.is_a? Array
memo[key.to_i]
else
key_to_sym(memo).fetch key.to_sym
end
end
end
def get_values(order, shape)
shape.map do |key, value|
if value.is_a? Hash
get_values(order, value)
else
shape[key] = order.fetch_deep(value)
end
end
end
def change(shape)
self.replace(shape)
end
def reshape(shape)
get_values(self, shape)
change(shape)
end
end
class Array
def reshape(newshape)
self.map do |arr_hash|
arr_hash.reshape(newshape.dup) if arr_hash.is_a? Hash
end
end
end

Лог от изпълнението

▸ Покажи лога

История (1 версия и 0 коментара)

Натали обнови решението на 24.10.2016 00:02 (преди над 8 години)

▸ Покажи разликите
+class Hash
+ def key_to_sym(myhash)
+ myhash.keys.each do |key|
+ myhash[(key.to_sym rescue key) || key] = myhash.delete(key)
+ end
+ myhash
+ end
+
+ def fetch_deep(path)
+ path.split('.').reduce(key_to_sym(self)) do |memo, key|
+ if memo.is_a? Array
+ memo[key.to_i]
+ else
+ key_to_sym(memo).fetch key.to_sym
+ end
+ end
+ end
+
+ def get_values(order, shape)
+ shape.map do |key, value|
+ if value.is_a? Hash
+ get_values(order, value)
+ else
+ shape[key] = order.fetch_deep(value)
+ end
+ end
+ end
+
+ def change(shape)
+ self.replace(shape)
+ end
+
+ def reshape(shape)
+ get_values(self, shape)
+ change(shape)
+ end
+end
+
+class Array
+ def reshape(newshape)
+ self.map do |arr_hash|
+ arr_hash.reshape(newshape.dup) if arr_hash.is_a? Hash
+ end
+ end
+end