Решение на Първа задача от Веселин Николов

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

Към профила на Веселин Николов

Резултати

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

Код

class Array
def to_hash
Hash[*self.flatten]
end
def index_by
hash = {}
self.each { |element| hash[yield element] = element }
return hash
end
def subarray_count array
subarrays_count = 0
self.each_index { |index| subarrays_count += 1 if self[index...index + array.length] == array }
return subarrays_count
end
def occurences_count
hash = Hash.new(0)
self.each do |element|
if hash.has_key?(element)
hash[element] = hash[element] + 1
else
hash[element] = 1
end
end
return hash
end
end

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

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

Failures:

  1) Array#to_hash works when the keys and values are arrays
     Failure/Error: [[1, [2, 3]], [[4, 5], 6]].to_hash.should eq(1 => [2, 3], [4, 5] => 6)
       
       expected {1=>[2, 3], [4, 5]=>6}
            got {1=>2, 3=>4, 5=>6}
       
       (compared using ==)
       
       Diff:
       @@ -1,2 +1,2 @@
       -{1=>[2, 3], [4, 5]=>6}
       +{1=>2, 3=>4, 5=>6}
     # /tmp/d20111025-2903-180gmdf/spec.rb:11:in `block (2 levels) in <top (required)>'
     # ./lib/homework/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/homework/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

Finished in 0.01962 seconds
17 examples, 1 failure

Failed examples:

rspec /tmp/d20111025-2903-180gmdf/spec.rb:10 # Array#to_hash works when the keys and values are arrays

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

Веселин обнови решението на 23.10.2011 20:56 (преди над 12 години)

+class Array
+ def to_hash
+ Hash[*self.flatten]
+ end
+
+ def index_by
+ hash = {}
+ self.each { |element| hash[yield element] = element }
+ return hash
+ end
+
+ def subarray_count array
+ subarrays_count = 0
+ self.each_index { |index| subarrays_count += 1 if self[index...index + array.length] == array }
+ return subarrays_count
+ end
+
+ def occurences_count
+ hash = Hash.new(0)
+ self.each do |element|
+ if hash.has_key?(element)
+ hash[element] = hash[element] + 1
+ else
+ hash[element] = 1
+ end
+ end
+ return hash
+ end
+end