Николай обнови решението на 23.10.2011 22:03 (преди около 13 години)
+class Array
+ def to_hash()
+ hash = {}
+ self.each do |array_element|
+ if hash.keys.include?(array_element[0])
+ hash[array_element[0]] = array_element[1]
+ else
+ hash[array_element[0]] = array_element[1]
+ end
+ end
+ hash
+ end
+
+ def index_by()
+ hash = {}
+ self.each { |array_element| hash[yield(array_element)] = array_element }
+ hash
+ end
+
+ def subarray_count(subarray)
+ if subarray == []
+ raise ArgumentError, "subarray cannot be []"
+ elsif self.size < subarray.size
+ return 0
+ elsif self == subarray
+ return 1
+ else
+ founded_subarrays = 0
+ self.size.times do |index|
+ sliced_array = self[index, subarray.size]
+ break if sliced_array.size < subarray.size
+ founded_subarrays += 1 if sliced_array == subarray
+ end
+ founded_subarrays
+ end
+ end
+
+ def occurences_count()
+ hash_with_occurences_count = Hash.new(0)
+ self.each do |key|
+ if hash_with_occurences_count.keys.include?(key)
+ hash_with_occurences_count[key] += 1
+ else
+ hash_with_occurences_count[key] = 1
+ end
+ end
+ hash_with_occurences_count
+ end
+end