Решение на Първа задача от Атанас Иларионов

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

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

Резултати

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

Код

class Array
def to_hash
result = Hash[*self.flatten]
end
def index_by
result = {}
self.each do |element|
key = yield element
result.merge!({key => element})
end
result
end
def subarray_count(subarray)
result = 0
size = subarray.length - 1
self.each_index do |i|
result = result + 1 if self[i..i+size].eql?(subarray)
end
result
end
def occurences_count
result = Hash.new(0)
self.each do |a|
value = self.count(a)
result.merge!(a => value)
end
result
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-140iot/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.01617 seconds
17 examples, 1 failure

Failed examples:

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

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

Атанас обнови решението на 24.10.2011 00:22 (преди над 12 години)

+class Array
+
+ def to_hash
+ result = Hash[*self.flatten]
+ end
+
+ def index_by
+ result = {}
+ self.each do |element|
+ key = yield element
+ result.merge!({key => element})
+ end
+ result
+ end
+
+ def subarray_count(subarray)
+ result = 0
+ size = subarray.length - 1
+ self.each_index do |i|
+ result = result + 1 if self[i..i+size].eql?(subarray)
+ end
+ result
+ end
+
+ def occurences_count
+ result = Hash.new(0)
+ self.each do |a|
+ value = self.count(a)
+ result.merge!(a => value)
+ end
+ result
+ end
+end