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

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

Към профила на Мила Бянкова

Резултати

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

Код

class Hash
def fetch_deep(path)
self.fetch_deep_iteration(path.split("."))
end
def fetch_deep_iteration(path_array)
key = change_key_type(path_array[0])
return nil if key == nil
return self[key] if path_array.length == 1
self[key] = transform_array_to_hash(self[key]) if self[key].is_a?(Array)
self[key].fetch_deep_iteration(path_array[1..path_array.length])
end
def change_key_type(key)
if self[key.to_sym]
key = key.to_sym
elsif self[key]
key
else
nil
end
end
def transform_array_to_hash(array)
array.map do |element|
[array.index(element).to_s, element]
end.to_h
end
def reshape(shape)
shape.map do |key, value|
[
key,
value.is_a?(Hash) ? reshape(value) : fetch_deep(value)
]
end.to_h
end
end
class Array
def reshape(shape)
map do |element|
element.reshape(shape)
end
end
end

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

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

Finished in 0.00936 seconds
15 examples, 0 failures

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

Мила обнови решението на 23.10.2016 17:29 (преди над 7 години)

+class Hash
+ def fetch_deep(path)
+ self.fetch_deep_iteration(path.split("."))
+ end
+
+ def fetch_deep_iteration(path_array)
+ key = change_key_type(path_array[0])
+ return self[key] if path_array.length == 1
+ self[key] = transform_array_to_hash(self[key]) if self[key].is_a?(Array)
+ self[key].fetch_deep_iteration(path_array[1..path_array.length])
+ end
+
+ def change_key_type(key)
+ if self[key.to_sym]
+ key = key.to_sym
+ elsif self[key.to_i]
+ key = key.to_i
+ end
+ key
+ end
+
+ def transform_array_to_hash(array)
+ array.map do |element|
+ [array.index(element), element]
+ end.to_h
+ end
+
+ def reshape(shape)
+ shape.map do |key, value|
+ [
+ key,
+ value.is_a?(Hash) ? reshape(value) : fetch_deep(value)
+ ]
+ end.to_h
+ end
+end
+
+class Array
+ def reshape(shape)
+ map do |element|
+ element.reshape(shape)
+ end
+ end
+end

Мила обнови решението на 24.10.2016 15:58 (преди над 7 години)

class Hash
def fetch_deep(path)
self.fetch_deep_iteration(path.split("."))
end
def fetch_deep_iteration(path_array)
key = change_key_type(path_array[0])
+ return nil if key == nil
return self[key] if path_array.length == 1
self[key] = transform_array_to_hash(self[key]) if self[key].is_a?(Array)
self[key].fetch_deep_iteration(path_array[1..path_array.length])
end
def change_key_type(key)
if self[key.to_sym]
key = key.to_sym
- elsif self[key.to_i]
- key = key.to_i
+ elsif self[key]
+ key
+ else
+ nil
end
- key
end
def transform_array_to_hash(array)
array.map do |element|
- [array.index(element), element]
+ [array.index(element).to_s, element]
end.to_h
end
def reshape(shape)
shape.map do |key, value|
[
key,
value.is_a?(Hash) ? reshape(value) : fetch_deep(value)
]
end.to_h
end
end
class Array
def reshape(shape)
map do |element|
element.reshape(shape)
end
end
end