Решение на Втора задача - хешове, масиви и структура от Методи Димитров

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

Към профила на Методи Димитров

Резултати

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

Код

class Hash
private
def fetch_h_a(structure, index)
if structure.class == Array
structure[index.to_i]
elsif structure.class == Hash
structure.fetch(index.to_sym) { |key| structure[key.to_s] }
end
end
def fetch_next(path, hash)
if path.empty?
hash
else
fetch_next(path.drop(1), fetch_h_a(hash, path.first))
end
end
public
def fetch_deep(path)
fetch_next path.split('.'), self
end
def reshape(shape)
if shape.class == Hash
shape.map { |key, value| [key, reshape(value)] }.to_h
else
fetch_deep(shape)
end
end
end
class Array
def reshape(shape)
map { |element| element.reshape(shape) }
end
end

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

...............

Finished in 0.00795 seconds
15 examples, 0 failures

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

Методи обнови решението на 24.10.2016 13:46 (преди над 7 години)

+class Hash
+ private
+
+ def fetch_h_a(structure, index)
+ if structure.class == Array
+ structure[index.to_i]
+ elsif structure.class == Hash
+ structure.fetch(index.to_sym) { |key| structure[key.to_s] }
+ end
+ end
+
+ def fetch_next(path, hash)
+ if path.empty?
+ hash
+ else
+ fetch_next(path.drop(1), fetch_h_a(hash, path.first))
+ end
+ end
+
+ public
+
+ def fetch_deep(path)
+ fetch_next path.split('.'), self
+ end
+
+ def reshape(shape)
+ if shape.class == Hash
+ shape.map { |key, value| [key, reshape(value)] }.to_h
+ else
+ fetch_deep(shape)
+ end
+ end
+end
+
+class Array
+ def reshape(shape)
+ map { |element| element.reshape(shape) }
+ end
+end