Решение на Втора задача от Мартин Христов

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

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

Резултати

  • 3 точки от тестове
  • 0 бонус точки
  • 3 точки общо
  • 13 успешни тест(а)
  • 11 неуспешни тест(а)

Код

class NumberSet
include Enumerable
def initialize *set
@set = set
end
def each &block
@set.each(block)
end
def <<(digit)
if (@set.include? digit)
return
else
@set.push(digit)
end
NumberSet.new(@set)
end
def size
@set.size
end
def empty?
@set.empty?
end
def [](filters)
if filters.class == Array
case filters[2]
when '&' then filtering [filters[0], filters[1]], '&'
when '|' then filtering [filters[0], filters[1]], '|'
end
else
filters.filter_array(@set)
end
end
def filtering filters, sign
temp_arrays = []
filters.each do |filter|
temp_arrays.push(filter.filter_array(@set))
end
case sign
when '&' then temp_arrays[0] & temp_arrays[1]
when '|' then temp_arrays[0] | temp_arrays[1]
end
end
end
class Filter
def initialize &block
@final_block = block
end
def &(second)
filter_types = [self, second, '&']
end
def |(second)
filter_types = [self, second, '|']
end
def filter_array numbers_array
result = []
numbers_array.each do |item|
if(@final_block.call(item) == true)
result.push(item)
end
end
result
end
end
class SignFilter < Filter
def initialize sign
@sign = sign
end
def filter_array numbers_array
case @sign
when :positive then numbers_array.delete_if { |n| n <= 0 }
when :negative then numbers_array.delete_if { |n| n >= 0 }
when :non_positive then numbers_array.delete_if { |n| n > 0 }
when :non_negative then numbers_array.delete_if { |n| n < 0 }
end
end
end
class TypeFilter < Filter
def initialize type
@type = type
end
def filter_array numbers_array
case @type
when :integer
filter_type_array numbers_array, Fixnum
when :complex
filter_type_array numbers_array, Complex
else
float_arr = filter_type_array numbers_array, Float
rat_arr = filter_type_array numbers_array, Rational
float_arr + rat_arr
end
end
def filter_type_array array, filter_type
filtered_array = []
array.each do |item|
if(item.class == filter_type)
filtered_array.push(item)
end
end
filtered_array
end
end

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

FFFFF.............FFFFFF

Failures:

  1) NumberSet can store integers
     Failure/Error: expect(numbers).to include and_get_it_as
     ArgumentError:
       wrong number of arguments (1 for 0)
     # /tmp/d20141028-18133-15r36ib/solution.rb:9:in `each'
     # /tmp/d20141028-18133-15r36ib/solution.rb:9:in `each'
     # /tmp/d20141028-18133-15r36ib/spec.rb:171:in `can_store'
     # /tmp/d20141028-18133-15r36ib/spec.rb:3:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  2) NumberSet can store floating point numbers
     Failure/Error: expect(numbers).to include and_get_it_as
     ArgumentError:
       wrong number of arguments (1 for 0)
     # /tmp/d20141028-18133-15r36ib/solution.rb:9:in `each'
     # /tmp/d20141028-18133-15r36ib/solution.rb:9:in `each'
     # /tmp/d20141028-18133-15r36ib/spec.rb:171:in `can_store'
     # /tmp/d20141028-18133-15r36ib/spec.rb:7:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  3) NumberSet can store complex numbers
     Failure/Error: expect(numbers).to include and_get_it_as
     ArgumentError:
       wrong number of arguments (1 for 0)
     # /tmp/d20141028-18133-15r36ib/solution.rb:9:in `each'
     # /tmp/d20141028-18133-15r36ib/solution.rb:9:in `each'
     # /tmp/d20141028-18133-15r36ib/spec.rb:171:in `can_store'
     # /tmp/d20141028-18133-15r36ib/spec.rb:11:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  4) NumberSet can store rational numbers
     Failure/Error: expect(numbers).to include and_get_it_as
     ArgumentError:
       wrong number of arguments (1 for 0)
     # /tmp/d20141028-18133-15r36ib/solution.rb:9:in `each'
     # /tmp/d20141028-18133-15r36ib/solution.rb:9:in `each'
     # /tmp/d20141028-18133-15r36ib/spec.rb:171:in `can_store'
     # /tmp/d20141028-18133-15r36ib/spec.rb:15:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  5) NumberSet can compare numbers of different types
     Failure/Error: expect(numbers).to include and_get_it_as
     ArgumentError:
       wrong number of arguments (1 for 0)
     # /tmp/d20141028-18133-15r36ib/solution.rb:9:in `each'
     # /tmp/d20141028-18133-15r36ib/solution.rb:9:in `each'
     # /tmp/d20141028-18133-15r36ib/spec.rb:171:in `can_store'
     # /tmp/d20141028-18133-15r36ib/spec.rb:19:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  6) NumberSet can combine multiple filters with "and" rule
     Failure/Error: filter        = non_negative & non_zero & mod_3_is_zero
     TypeError:
       no implicit conversion of Filter into Array
     # /tmp/d20141028-18133-15r36ib/spec.rb:108:in `&'
     # /tmp/d20141028-18133-15r36ib/spec.rb:108:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  7) NumberSet can combine multiple filters with "or" rule
     Failure/Error: filter        = even | negative | more_than_100
     TypeError:
       no implicit conversion of Filter into Array
     # /tmp/d20141028-18133-15r36ib/spec.rb:118:in `|'
     # /tmp/d20141028-18133-15r36ib/spec.rb:118:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  8) NumberSet can combine multiple filters with "and" and "or" rules
     Failure/Error: filter        = even & negative | mod_3_is_zero
     TypeError:
       no implicit conversion of Filter into Array
     # /tmp/d20141028-18133-15r36ib/spec.rb:128:in `|'
     # /tmp/d20141028-18133-15r36ib/spec.rb:128:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  9) NumberSet can combine multiple filters with "and", "or" and parenthesis
     Failure/Error: filtered_numbers = numbers[using]
     NoMethodError:
       undefined method `filter_array' for #<Array:0xb9e548f4>
     # /tmp/d20141028-18133-15r36ib/solution.rb:43:in `block in filtering'
     # /tmp/d20141028-18133-15r36ib/solution.rb:42:in `each'
     # /tmp/d20141028-18133-15r36ib/solution.rb:42:in `filtering'
     # /tmp/d20141028-18133-15r36ib/solution.rb:32:in `[]'
     # /tmp/d20141028-18133-15r36ib/spec.rb:179:in `can_filter'
     # /tmp/d20141028-18133-15r36ib/spec.rb:139:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  10) NumberSet is enumerable
     Failure/Error: numbers.each do |number|
     ArgumentError:
       wrong number of arguments (1 for 0)
     # /tmp/d20141028-18133-15r36ib/solution.rb:9:in `each'
     # /tmp/d20141028-18133-15r36ib/solution.rb:9:in `each'
     # /tmp/d20141028-18133-15r36ib/spec.rb:152:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

  11) NumberSet returns enumerable of set's contents if no block is given to each
     Failure/Error: expect(numbers.each.to_a.size).to eq [1, 3, 5].size
     ArgumentError:
       wrong number of arguments (1 for 0)
     # /tmp/d20141028-18133-15r36ib/solution.rb:9:in `each'
     # /tmp/d20141028-18133-15r36ib/solution.rb:9:in `each'
     # /tmp/d20141028-18133-15r36ib/spec.rb:164:in `block (2 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/language/ruby/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

Finished in 0.02183 seconds
24 examples, 11 failures

Failed examples:

rspec /tmp/d20141028-18133-15r36ib/spec.rb:2 # NumberSet can store integers
rspec /tmp/d20141028-18133-15r36ib/spec.rb:6 # NumberSet can store floating point numbers
rspec /tmp/d20141028-18133-15r36ib/spec.rb:10 # NumberSet can store complex numbers
rspec /tmp/d20141028-18133-15r36ib/spec.rb:14 # NumberSet can store rational numbers
rspec /tmp/d20141028-18133-15r36ib/spec.rb:18 # NumberSet can compare numbers of different types
rspec /tmp/d20141028-18133-15r36ib/spec.rb:104 # NumberSet can combine multiple filters with "and" rule
rspec /tmp/d20141028-18133-15r36ib/spec.rb:114 # NumberSet can combine multiple filters with "or" rule
rspec /tmp/d20141028-18133-15r36ib/spec.rb:124 # NumberSet can combine multiple filters with "and" and "or" rules
rspec /tmp/d20141028-18133-15r36ib/spec.rb:134 # NumberSet can combine multiple filters with "and", "or" and parenthesis
rspec /tmp/d20141028-18133-15r36ib/spec.rb:144 # NumberSet is enumerable
rspec /tmp/d20141028-18133-15r36ib/spec.rb:159 # NumberSet returns enumerable of set's contents if no block is given to each

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

Мартин обнови решението на 21.10.2014 22:57 (преди около 10 години)

+class NumberSet
+ include Enumerable
+
+ def initialize
+ @numbers = []
+ end
+
+ def <<(digit)
+ @numbers.each do |item|
+ if(item == digit)
+ return
+ end
+ end
+ @numbers.push(digit)
+ end
+
+ def size
+ @numbers.length
+ end
+
+ def empty?
+ @numbers.empty?
+ end
+
+ def [](arguments)
+ case arguments[2]
+ when '&'
+ and_filters [arguments[0], arguments[1]]
+ else
+ or_filters [arguments[0], arguments[1]]
+ end
+ end
+
+ def and_filters filters
+ temp_arrays = []
+ filters.each do |filter|
+ if (filter.class == Filter)
+ temp_arrays.push(filter.filter_array(@numbers))
+ elsif (filter.class == TypeFilter)
+ temp_arrays.push(filter.type_array(@numbers))
+ else
+ temp_arrays.push(filter.sign_array(@numbers))
+ end
+ end
+ temp_arrays[0] & temp_arrays[1]
+ end
+
+ def or_filters filters
+ temp_arrays = []
+ filters.each do |filter|
+ if (filter.class == Filter)
+ temp_arrays.push(filter.filter_array(@numbers))
+ elsif (filter.class == TypeFilter)
+ temp_arrays.push(filter.type_array(@numbers))
+ else
+ temp_arrays.push(filter.sign_array(@numbers))
+ end
+ end
+ temp_arrays[0] | temp_arrays[1]
+ end
+end
+
+class BaseFilter
+ def &(second)
+ filter_types = [self, second, '&']
+ end
+
+ def |(second)
+ filter_types = [self, second, '|']
+ end
+end
+
+class SignFilter < BaseFilter
+ def initialize argument
+ @argument = argument
+ end
+
+ def sign_array numbers_array
+ case @argument
+ when :positive then filter_positive_array(numbers_array)
+ when :negative then filter_negative_array(numbers_array)
+ when :non_positive then filter_non_positive_array(numbers_array)
+ when :non_negative then filter_non_negative_array(numbers_array)
+ end
+ end
+
+ def filter_positive_array array
+ filtered_positive_array = []
+ array.each do |item|
+ if (item > 0)
+ filtered_positive_array.push(item)
+ end
+ end
+ return filtered_positive_array
+ end
+
+ def filter_negative_array array
+ filtered_negative_array = []
+ array.each do |item|
+ if (item < 0)
+ filtered_negative_array.push(item)
+ end
+ end
+ return filtered_negative_array
+ end
+
+ def filter_non_positive_array array
+ filtered_non_positive_array = []
+ array.each do |item|
+ if (item <= 0)
+ filtered_non_positive_array.push(item)
+ end
+ end
+ return filtered_non_positive_array
+ end
+
+ def filter_non_negative_array array
+ filtered_non_negative_array = []
+ array.each do |item|
+ if (item >= 0)
+ filtered_non_negative_array.push(item)
+ end
+ end
+ return filtered_non_negative_array
+ end
+end
+
+class TypeFilter < BaseFilter
+ def initialize argument
+ @argument = argument
+ end
+
+ def type_array numbers_array
+ case @argument
+ when :integer
+ filter_type_array numbers_array, Fixnum
+ when :complex
+ filter_type_array numbers_array, Complex
+ else
+ float_arr = filter_type_array numbers_array, Float
+ rat_arr = filter_type_array numbers_array, Rational
+ float_arr + rat_arr
+ end
+ end
+
+ def filter_type_array array, filter_type
+ filtered_array = []
+ array.each do |item|
+ if(item.class == filter_type)
+ filtered_array.push(item)
+ end
+ end
+ return filtered_array
+ end
+end
+
+class Filter < BaseFilter
+ def initialize &block
+ @final_block = block
+ end
+
+ def filter_array numbers_array
+ result = []
+ numbers_array.each do |item|
+ if(@final_block.call(item) == true)
+ result.push(item)
+ end
+ end
+ return result
+ end
+end

Мартин обнови решението на 22.10.2014 00:35 (преди около 10 години)

class NumberSet
include Enumerable
def initialize
@numbers = []
end
def <<(digit)
@numbers.each do |item|
if(item == digit)
return
end
end
@numbers.push(digit)
end
def size
@numbers.length
end
def empty?
@numbers.empty?
end
def [](arguments)
- case arguments[2]
- when '&'
- and_filters [arguments[0], arguments[1]]
+ if arguments.class == Array
+ case arguments[2]
+ when '&' then and_filters [arguments[0], arguments[1]]
+ when '|' then or_filters [arguments[0], arguments[1]]
+ end
else
- or_filters [arguments[0], arguments[1]]
+ if (arguments.class == Filter) then arguments.filter_array(@numbers)
+ elsif (arguments.class == TypeFilter) then arguments.type_array(@numbers)
+ else
+ arguments.sign_array(@numbers)
+ end
end
end
def and_filters filters
temp_arrays = []
filters.each do |filter|
if (filter.class == Filter)
temp_arrays.push(filter.filter_array(@numbers))
elsif (filter.class == TypeFilter)
temp_arrays.push(filter.type_array(@numbers))
else
temp_arrays.push(filter.sign_array(@numbers))
end
end
temp_arrays[0] & temp_arrays[1]
end
def or_filters filters
temp_arrays = []
filters.each do |filter|
if (filter.class == Filter)
temp_arrays.push(filter.filter_array(@numbers))
elsif (filter.class == TypeFilter)
temp_arrays.push(filter.type_array(@numbers))
else
temp_arrays.push(filter.sign_array(@numbers))
end
end
temp_arrays[0] | temp_arrays[1]
end
end
class BaseFilter
def &(second)
filter_types = [self, second, '&']
end
def |(second)
filter_types = [self, second, '|']
end
end
class SignFilter < BaseFilter
def initialize argument
@argument = argument
end
def sign_array numbers_array
case @argument
when :positive then filter_positive_array(numbers_array)
when :negative then filter_negative_array(numbers_array)
when :non_positive then filter_non_positive_array(numbers_array)
when :non_negative then filter_non_negative_array(numbers_array)
end
end
def filter_positive_array array
filtered_positive_array = []
array.each do |item|
if (item > 0)
filtered_positive_array.push(item)
end
end
return filtered_positive_array
end
def filter_negative_array array
filtered_negative_array = []
array.each do |item|
if (item < 0)
filtered_negative_array.push(item)
end
end
return filtered_negative_array
end
def filter_non_positive_array array
filtered_non_positive_array = []
array.each do |item|
if (item <= 0)
filtered_non_positive_array.push(item)
end
end
return filtered_non_positive_array
end
def filter_non_negative_array array
filtered_non_negative_array = []
array.each do |item|
if (item >= 0)
filtered_non_negative_array.push(item)
end
end
return filtered_non_negative_array
end
end
class TypeFilter < BaseFilter
def initialize argument
@argument = argument
end
def type_array numbers_array
case @argument
when :integer
filter_type_array numbers_array, Fixnum
when :complex
filter_type_array numbers_array, Complex
else
float_arr = filter_type_array numbers_array, Float
rat_arr = filter_type_array numbers_array, Rational
float_arr + rat_arr
end
end
def filter_type_array array, filter_type
filtered_array = []
array.each do |item|
if(item.class == filter_type)
filtered_array.push(item)
end
end
return filtered_array
end
end
class Filter < BaseFilter
def initialize &block
@final_block = block
end
def filter_array numbers_array
result = []
numbers_array.each do |item|
if(@final_block.call(item) == true)
result.push(item)
end
end
return result
end
end

Предал си рано, още преди да преподадем нещата. Много похвално! Все пак има известно количество проблеми, някои от тях доста важни:

  • Има още нещо, което трябва да се направи, за да се възползваш от Enumerable, освен include Enumerable. Можеш да прочетеш пак условието, разгледаш в интернет и/или да изчакаш лекцията довечера.
  • Логиката на NumberSet#[], NumberSet#and_filters и NumberSet#or_filters прави това, което филтрите трябва да правят. Изнеси я там. Както сам виждаш си направил доста хакарии, за да успееш да я подкараш в сегашната версия. Даваш имена на методи като низове и switch-ваш по тях. Сравняваш за типа на обекти от класове, които ти си дефинирал. Не че по принцип да сравняваш за типа на обекти от core класове е нещо добро, но тук експлицитно сме ви накарали да го направите. Какво ще стане, ако поискаме да сложите още един вид филтър или нова операция върху филтри? Всичко това може да се постигне по много по-кратък и лесен начин. Hint: блокове.
  • Беше ли нужен BaseFilter изобщо? Не можеше ли SignFilter и TypeFilter да наследяват от Filter?
  • SignFilter#sign_array, SignFilter#filter_positive_array, SignFilter#filter_negative_array, SignFilter#filter_non_positive_array, SignFilter#filter_non_negative_array, TypeFilter#type_array, TypeFilter#filter_type_array са всички доста по-сложни, отколкото е нужно. Някои повтарят сходна логика. Нямаше ли да е по-лесно, консистентно и приятно, ако в NumberSet се викаше само един метод, който просто да филтрира, независимо какви филтри се подават? Hint: отново блокове. (:

NB: не се притеснявай, блоковете са концепция в Ruby, която не е много интуитивна, идвайки от други езици. Също е и изключително важна, изосновна и магически удобна такава. Осъзнаваме това и днес отново ще дълбаем в нея.

  • NumberSet#<< също е малко по-сложно с този обърнат словоред. Разгледай документацията на Array#include? и как работи == за различните видове числа.
  • Имаш няколко нарушения на конвенцията, погледни style guide-а, за да ги адресираш. Главно малко whitespace неща и липсващи/присъстващи скоби, където не трябва.
  • Опитай се да измисляш по-добри имена. digit леко лъже, понеже подаваме числа, а не цифри на NumberSet#<<. Защо NumberSet#size си го имплементирал с @numbers.length, не е ли по-звучно с Array#size? arguments, temp_arrays, @argument, numbers_array, array, item, float_arr и result са все много general имена. Извън контекст не ми говорят нищо и трябва да интерпретирам кода наум, за да разбера каква е идеята им. Можеш да кръстиш аргументите на абсолютно всеки един метод arguments, опитвай се имената да изказват точно и ясно идеята на това, което съдържат в дадената ситуация. Например в конструктора на TypeFilter, вместо argument можеше да сложиш type или number_type, веднага става ясно каква е семантиката. Не съкращавай букви, не печелиш нищо, а става по-трудно за разбиране. Не слагай array, hash и т.н. като префикс/суфикс/където и да е по средата в имената. Човекът, който чете кода не трябва да се интересува дали това е масив или не е масив. Единствено какво значи променливата за задачата. temp и result също не значат нищо сами по себе си и трябва да се избягват в 99% от случаите.

Мартин обнови решението на 24.10.2014 01:13 (преди около 10 години)

class NumberSet
include Enumerable
- def initialize
- @numbers = []
+ def initialize *set
+ @set = set
end
+ def each &block
+ @set.each(block)
+ end
+
def <<(digit)
- @numbers.each do |item|
- if(item == digit)
- return
- end
+ if (@set.include? digit)
+ return
+ else
+ @set.push(digit)
end
- @numbers.push(digit)
+ NumberSet.new(@set)
end
def size
- @numbers.length
+ @set.size
end
def empty?
- @numbers.empty?
+ @set.empty?
end
- def [](arguments)
- if arguments.class == Array
- case arguments[2]
- when '&' then and_filters [arguments[0], arguments[1]]
- when '|' then or_filters [arguments[0], arguments[1]]
+ def [](filters)
+ if filters.class == Array
+ case filters[2]
+ when '&' then filtering [filters[0], filters[1]], '&'
+ when '|' then filtering [filters[0], filters[1]], '|'
end
else
- if (arguments.class == Filter) then arguments.filter_array(@numbers)
- elsif (arguments.class == TypeFilter) then arguments.type_array(@numbers)
- else
- arguments.sign_array(@numbers)
- end
+ filters.filter_array(@set)
end
end
- def and_filters filters
+ def filtering filters, sign
temp_arrays = []
filters.each do |filter|
- if (filter.class == Filter)
- temp_arrays.push(filter.filter_array(@numbers))
- elsif (filter.class == TypeFilter)
- temp_arrays.push(filter.type_array(@numbers))
- else
- temp_arrays.push(filter.sign_array(@numbers))
- end
+ temp_arrays.push(filter.filter_array(@set))
end
- temp_arrays[0] & temp_arrays[1]
- end
-
- def or_filters filters
- temp_arrays = []
- filters.each do |filter|
- if (filter.class == Filter)
- temp_arrays.push(filter.filter_array(@numbers))
- elsif (filter.class == TypeFilter)
- temp_arrays.push(filter.type_array(@numbers))
- else
- temp_arrays.push(filter.sign_array(@numbers))
- end
+ case sign
+ when '&' then temp_arrays[0] & temp_arrays[1]
+ when '|' then temp_arrays[0] | temp_arrays[1]
end
- temp_arrays[0] | temp_arrays[1]
end
end
-class BaseFilter
+class Filter
+ def initialize &block
+ @final_block = block
+ end
+
def &(second)
filter_types = [self, second, '&']
end
def |(second)
filter_types = [self, second, '|']
end
-end
-class SignFilter < BaseFilter
- def initialize argument
- @argument = argument
- end
-
- def sign_array numbers_array
- case @argument
- when :positive then filter_positive_array(numbers_array)
- when :negative then filter_negative_array(numbers_array)
- when :non_positive then filter_non_positive_array(numbers_array)
- when :non_negative then filter_non_negative_array(numbers_array)
- end
- end
-
- def filter_positive_array array
- filtered_positive_array = []
- array.each do |item|
- if (item > 0)
- filtered_positive_array.push(item)
+ def filter_array numbers_array
+ result = []
+ numbers_array.each do |item|
+ if(@final_block.call(item) == true)
+ result.push(item)
end
end
- return filtered_positive_array
+ result
end
+end
- def filter_negative_array array
- filtered_negative_array = []
- array.each do |item|
- if (item < 0)
- filtered_negative_array.push(item)
- end
- end
- return filtered_negative_array
+class SignFilter < Filter
+ def initialize sign
+ @sign = sign
end
- def filter_non_positive_array array
- filtered_non_positive_array = []
- array.each do |item|
- if (item <= 0)
- filtered_non_positive_array.push(item)
- end
+ def filter_array numbers_array
+ case @sign
+ when :positive then numbers_array.delete_if { |n| n <= 0 }
+ when :negative then numbers_array.delete_if { |n| n >= 0 }
+ when :non_positive then numbers_array.delete_if { |n| n > 0 }
+ when :non_negative then numbers_array.delete_if { |n| n < 0 }
end
- return filtered_non_positive_array
end
-
- def filter_non_negative_array array
- filtered_non_negative_array = []
- array.each do |item|
- if (item >= 0)
- filtered_non_negative_array.push(item)
- end
- end
- return filtered_non_negative_array
- end
end
-class TypeFilter < BaseFilter
- def initialize argument
- @argument = argument
+class TypeFilter < Filter
+ def initialize type
+ @type = type
end
- def type_array numbers_array
- case @argument
+ def filter_array numbers_array
+ case @type
when :integer
filter_type_array numbers_array, Fixnum
when :complex
filter_type_array numbers_array, Complex
else
float_arr = filter_type_array numbers_array, Float
rat_arr = filter_type_array numbers_array, Rational
float_arr + rat_arr
end
end
def filter_type_array array, filter_type
filtered_array = []
array.each do |item|
if(item.class == filter_type)
filtered_array.push(item)
end
end
- return filtered_array
- end
-end
-
-class Filter < BaseFilter
- def initialize &block
- @final_block = block
- end
-
- def filter_array numbers_array
- result = []
- numbers_array.each do |item|
- if(@final_block.call(item) == true)
- result.push(item)
- end
- end
- return result
+ filtered_array
end
end