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

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

Към профила на Георги Иванов

Резултати

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

Код

class Hash
def fetch_deep(path)
key, rest = path.to_s.partition('.').values_at(0, -1)
value = (self.key? key) ? self[key] : self[key.to_sym]
if value.nil? || rest.empty?
value
else
value.fetch_deep(rest)
end
end
def reshape(shape)
shape.each_pair do |key, value|
shape = {key => reshape(value)} if value.is_a? Hash
reshape(value) if value.is_a? Array
shape[key] = fetch_deep(value)
shape
end
end
end
class Array
def fetch_deep(path)
index, rest = path.partition('.').values_at(0, -1)
value = self[index.to_i]
if value.nil? || rest.empty?
value
else
value.fetch_deep(rest)
end
end
def reshape(shape)
map { |element| element.reshape(shape.clone) }
end
end

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

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

Finished in 0.00803 seconds
15 examples, 0 failures

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

Георги обнови решението на 23.10.2016 22:35 (преди над 7 години)

+class Hash
+ def fetch_deep(path)
+ key, rest = path.to_s.partition('.').values_at(0, -1)
+ value = (self.key? key) ? self[key] : self[key.to_sym]
+ if value.nil? || rest.empty?
+ value
+ else
+ value.fetch_deep(rest)
+ end
+ end
+
+ def reshape(shape)
+ result = shape.clone
+ result.each_key do |key|
+ reshape(result[key]) if result[key].is_a? Hash
+ reshape(result[key]) if result[key].is_a? Array
+ result[key] = fetch_deep(result[key])
+ result
+ end
+ end
+end
+
+class Array
+ def fetch_deep(path)
+ index, rest = path.partition('.').values_at(0, -1)
+ value = self[index.to_i]
+ if value.nil? || rest.empty?
+ value
+ else
+ value.fetch_deep(rest)
+ end
+ end
+
+ def reshape(shape)
+ map { |element| element.reshape(shape) }
+ end
+end

Георги обнови решението на 24.10.2016 08:23 (преди над 7 години)

class Hash
def fetch_deep(path)
key, rest = path.to_s.partition('.').values_at(0, -1)
value = (self.key? key) ? self[key] : self[key.to_sym]
if value.nil? || rest.empty?
value
else
value.fetch_deep(rest)
end
end
def reshape(shape)
- result = shape.clone
- result.each_key do |key|
- reshape(result[key]) if result[key].is_a? Hash
- reshape(result[key]) if result[key].is_a? Array
- result[key] = fetch_deep(result[key])
- result
+ shape.each_pair do |key, value|
+ shape = {key => reshape(value)} if value.is_a? Hash
+ reshape(value) if value.is_a? Array
+ shape[key] = fetch_deep(value)
+ shape
end
end
end
class Array
def fetch_deep(path)
index, rest = path.partition('.').values_at(0, -1)
value = self[index.to_i]
if value.nil? || rest.empty?
value
else
value.fetch_deep(rest)
end
end
def reshape(shape)
- map { |element| element.reshape(shape) }
+ map { |element| element.reshape(shape.clone) }
end
-end
+end