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

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

Към профила на Христо Кирилов

Резултати

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

Код

class Hash
def fetch_deep(path)
fetch_deep_helper path, self
end
def reshape(shape)
new_hash = {}
shape.each do |k, v|
new_hash[k] = v.is_a?(String) ? fetch_deep(v) : reshape(shape[k])
end
replace new_hash
new_hash
end
def fetch_deep_helper(path, hash)
return hash if path.nil? || hash.nil?
path = path.split '.', 2
first = path[0]
path = path[1]
hash = get_new_hash first, hash
fetch_deep_helper path, hash
end
def get_new_hash(path, hash)
if hash.is_a? Array
num = Integer path rescue nil
num.nil? ? nil : hash[num]
elsif !hash[path].nil?
hash[path]
else
hash[path.to_sym]
end
end
end
class Array
def reshape(shape)
each { |i| i.reshape(shape) }
end
end

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

.............F.

Failures:

  1) Task 2 Hash#reshape does not modify the input hash
     Failure/Error: expect(input).to eq menu: {
       
       expected: {:menu=>{:order=>"cake", "dessert"=>"ice cream", 3=>4}}
            got: {:order=>"cake", :dessert=>"ice cream"}
       
       (compared using ==)
       
       Diff:
       @@ -1,2 +1,3 @@
       -:menu => {:order=>"cake", "dessert"=>"ice cream", 3=>4}
       +:dessert => "ice cream",
       +:order => "cake"
     # /tmp/d20161024-13689-1u9srfl/spec.rb:196:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:7:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:7:in `block (2 levels) in <top (required)>'

Finished in 0.0088 seconds
15 examples, 1 failure

Failed examples:

rspec /tmp/d20161024-13689-1u9srfl/spec.rb:180 # Task 2 Hash#reshape does not modify the input hash

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

Христо обнови решението на 24.10.2016 15:58 (преди около 8 години)

+class Hash
+ def fetch_deep(path)
+ fetch_deep_helper path, self
+ end
+
+ def reshape(shape)
+ new_hash = {}
+ shape.each do |k, v|
+ new_hash[k] = v.is_a?(String) ? fetch_deep(v) : reshape(shape[k])
+ end
+ replace new_hash
+ new_hash
+ end
+
+ def fetch_deep_helper(path, hash)
+ return hash if path.nil? || hash.nil?
+ path = path.split '.', 2
+ first = path[0]
+ path = path[1]
+ hash = get_new_hash first, hash
+ fetch_deep_helper path, hash
+ end
+
+ def get_new_hash(path, hash)
+ if hash.is_a? Array
+ num = Integer path rescue nil
+ num.nil? ? nil : hash[num]
+ elsif !hash[path].nil?
+ hash[path]
+ else
+ hash[path.to_sym]
+ end
+ end
+end
+
+class Array
+ def reshape(shape)
+ each { |i| i.reshape(shape) }
+ end
+end