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

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

Към профила на Иван Арабаджиев

Резултати

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

Код

class Array
def to_hash
to_return = {}
self.each { |el| to_return[ el.first ] = el.last }
to_return
end
def index_by
raise ArgumentError unless block_given?
to_return = {}
self.each { |el| to_return[yield el] = el }
to_return
end
def subarray_count(subarray)
raise ArgumentException if subarray.empty?
to_return = 0
victim = self.dup
while victim.length >= subarray.length do
to_return += 1 if victim.first(subarray.length) == subarray
victim.shift
end
to_return
end
def occurences_count
to_return = Hash.new(0)
self.each do |el|
next if to_return.has_key? el
diff = self - Array(el)
to_return[el] = self.length - diff.length
end
to_return
end
end

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

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

Failures:

  1) Array#occurences_count works with arrays containing nil and false
     Failure/Error: [nil, false, nil, false, true].occurences_count.should eq(nil => 2, false => 2, true => 1)
       
       expected {nil=>2, false=>2, true=>1}
            got {nil=>0, false=>2, true=>1}
       
       (compared using ==)
       
       Diff:
       @@ -1,2 +1,2 @@
       -{nil=>2, false=>2, true=>1}
       +{nil=>0, false=>2, true=>1}
     # /tmp/d20111025-2903-fl6w7e/spec.rb:78: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.01625 seconds
17 examples, 1 failure

Failed examples:

rspec /tmp/d20111025-2903-fl6w7e/spec.rb:77 # Array#occurences_count works with arrays containing nil and false

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

Иван обнови решението на 19.10.2011 14:53 (преди над 12 години)

+class Array
+ def to_hash
+ to_return = {}
+ self.each { |el| to_return[ el.first ] = el.last }
+ to_return
+ end
+
+ def index_by
+ raise ArgumentError unless block_given?
+ to_return = {}
+ self.each { |el| to_return[yield el] = el }
+ to_return
+ end
+
+ def subarray_count(subarray)
+ raise ArgumentException if subarray.empty?
+ to_return = 0
+ victim = self.dup
+ while victim.length >= subarray.length do
+ to_return += 1 if victim.first(subarray.length) == subarray
+ victim.shift
+ end
+ to_return
+ end
+
+ def occurences_count
+ to_return = Hash.new(0)
+ self.each do |el|
+ next if to_return.has_key? el
+ diff = self - Array(el)
+ to_return[el] = self.length - diff.length
+ end
+ to_return
+ end
+end