Решение на Първа задача от Мартин Маринов

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

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

Резултати

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

Код

=begin
The best solution is:
class Array
def to_hash
Hash[*self.flatten(1)]
end
end
I haven't posted it because I'm afraid a lot of people are going
to use it in their code.
=end
class Array
def to_hash
new_hash = {}
self.each { | key, value | new_hash[key] = value }
new_hash
end
def index_by
new_hash = {}
self.each do | value |
key = yield value # yield is a lot faster than block.call()
new_hash[key] = value
end
new_hash
end
def subarray_count(subarray)
string_array = self.join('') # Converting into string
string_subarray = subarray.join('') # Converting into string
pattern = "(?=(#{string_subarray}))"
string_array.scan(Regexp.new(pattern)).length # Using Regexp
end
def occurences_count
new_hash = Hash.new(0)
self.each { |el| new_hash[el] += 1 }
new_hash
end
end

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

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

Finished in 0.01517 seconds
17 examples, 0 failures

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

Мартин обнови решението на 24.10.2011 02:06 (преди над 12 години)

+=begin
+The best solution is:
+
+class Array
+ def to_hash
+ Hash[*self.flatten(1)]
+ end
+end
+
+I haven't posted it because I'm afraid a lot of people are going
+to use it in their code.
+=end
+class Array
+ def to_hash
+ new_hash = {}
+ self.each { | key, value | new_hash[key] = value }
+ new_hash
+ end
+
+ def index_by
+ new_hash = {}
+ self.each do | value |
+ key = yield value # yield is a lot faster than block.call()
+ new_hash[key] = value
+ end
+ new_hash
+ end
+
+ def subarray_count(subarray)
+ string_array = self.join('') # Converting into string
+ string_subarray = subarray.join('') # Converting into string
+ pattern = "(?=(#{string_subarray}))"
+ string_array.scan(Regexp.new(pattern)).length # Using Regexp
+ end
+
+ def occurences_count
+ new_hash = Hash.new(0)
+ self.each { |el| new_hash[el] += 1 }
+ new_hash
+ end
+end