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

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

Към профила на Божидар Михайлов

Резултати

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

Код

class Hash
def fetch_key_from_collection(collection, key)
return collection[Integer(key)] if collection.is_a?(Array)
[key, key.to_sym, key.to_r, key.to_i].each do |k|
return collection[k] if collection.key? k
end
nil
end
def fetch_deep(path)
keys = path.split('.')
keys.reduce(self) do |coll, key|
return nil if coll.nil?
fetch_key_from_collection(coll, key)
end
end
def reshape(shape)
return fetch_deep(shape) if shape.is_a?(String)
shape.map { |k, v| [k, reshape(v)] } .to_h
end
end
class Array
def reshape(shape)
map { |hash| hash.reshape(shape) }
end
end

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

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

Finished in 0.00824 seconds
15 examples, 0 failures

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

Божидар обнови решението на 23.10.2016 14:53 (преди над 7 години)

+class Hash
+ def fetch_key_from_collection(collection, key)
+ return collection[Integer(key)] if collection.is_a?(Array)
+ [key, key.to_sym, key.to_r, key.to_i].each do |k|
+ return collection[k] if collection.key? k
+ end
+ nil
+ end
+
+ def fetch_deep(path)
+ keys = path.split('.')
+ keys.reduce(self) do |coll, key|
+ return nil if coll.nil?
+ fetch_key_from_collection(coll, key)
+ end
+ end
+
+ def reshape(shape)
+ return fetch_deep(shape) if shape.is_a?(String)
+ shape.map { |k, v| [k, reshape(v)] } .to_h
+ end
+end
+
+class Array
+ def reshape(shape)
+ map { |hash| hash.reshape(shape) }
+ end
+end
+