From b02f47bdf769cfe4f6691bbe29098a6cbb43ac0e Mon Sep 17 00:00:00 2001 From: gavroshcho Date: Thu, 3 Dec 2015 14:58:23 +0200 Subject: [PATCH] My enumerable --- week03/3-My-Enumerable/solution.rb | 109 ++++++++++++++++++++++++----- 1 file changed, 93 insertions(+), 16 deletions(-) diff --git a/week03/3-My-Enumerable/solution.rb b/week03/3-My-Enumerable/solution.rb index a6e7465..80d8624 100644 --- a/week03/3-My-Enumerable/solution.rb +++ b/week03/3-My-Enumerable/solution.rb @@ -10,66 +10,143 @@ def map end def filter - # Your code goes here + Array.new.tap do |arr| + each do |element| + arr << element if (yield element) == true + end + end end def reject - # Your code goes here + Array.new.tap do |arr| + each do |element| + arr << element if (yield element) == false + end + end end def reduce(initial = nil) - # Your code goes here + each do |element| + if initial.nil? + initial = element + else + initial = yield element, initial + end + end + initial end def any? - # Your code goes here + each do |element| + if (yield element) == false + false + else + return true + end + end end def all? - # Your code goes here + each do |element| + if (yield element) == false + return false + else + true + end + end end def include?(element) - # Your code goes here + each do |item| + if item == element + return true + else + false + end + end end def count(element = nil) - # Your code goes here + counter = 0 + each do |item| + counter += 1 if element.nil? + counter += 1 if item == element + end + counter end def size - # Your code goes here + counter = 0 + each do + counter += 1 + end + counter end def min - # Your code goes here. + reduce do |element, accumulator| + accumulator > element ? element : accumulator + end end def min_by - # Your code goes here. + reduce do |element, accumulator| + (yield accumulator) > element.size ? element : accumulator + end end def max - # Your code goes here. + reduce do |element, accumulator| + accumulator < element ? element : accumulator + end end def max_by - # Your code goes here. + reduce do |element, accumulator| + (yield accumulator) < element.size ? element : accumulator + end end def take(n) - # Your code goes here. + counter = 0 + Array.new.tap do |arr| + each do |element| + return Array.new if n == 0 + arr << element + counter += 1 + break if counter == n + end + end end def take_while - # Your code goes here. + Array.new.tap do |arr| + each do |element| + if (yield element) == true + arr << element + else + break + end + end + return [] if arr.size == 0 + end end def drop(n) - # Your code goes here. + counter = 0 + Array.new.tap do |arr| + each do |element| + arr << element if counter >= n + counter += 1 + end + end end def drop_while - # Your code goes here. + counter = 0 + each do |element| + counter += 1 if (yield element) == true + return drop(counter) if (yield element) == false + end end end