Дамян обнови решението на 26.10.2014 13:19 (преди около 10 години)
+class NumberSet
+ include Enumerable
+
+ def initialize
+ @numbers = []
+ end
+
+ def each(&block)
+ @numbers.each(&block)
+ end
+
+ def <<(other)
+ @numbers << other if all? { |number| number != other }
+ end
+
+ def size
+ count
+ end
+
+ def empty?
+ count == 0 ? true : false
+ end
+
+ def [](filter)
+ filter_result = NumberSet.new
+ @numbers.each { |number| filter_result << number if filter.met_by? number }
+ filter_result
+ end
+end
+
+class Filter
+ def initialize(&filter)
+ @filter = filter
+ end
+
+ def met_by?(number)
+ @filter.call(number)
+ end
+
+ def &(other)
+ Filter.new { |number| met_by?(number) and other.met_by?(number) }
+ end
+
+ def |(other)
+ Filter.new { |number| met_by?(number) or other.met_by?(number) }
+ end
+end
+
+class SignFilter
+ def initialize(filter)
+ if filter == :positive
+ @filter = Proc.new { |number| number > 0}
+ elsif filter == :non_positive
+ @filter = Proc.new { |number| number <= 0}
+ elsif filter == :negative
+ @filter = Proc.new { |number| number < 0}
+ elsif filter == :non_negative
+ @filter = Proc.new { |number| number >= 0}
+ end
+ end
+
+ def met_by?(number)
+ @filter.call(number)
+ end
+
+ def &(other)
+ Filter.new { |number| met_by?(number) and other.met_by?(number) }
+ end
+
+ def |(other)
+ Filter.new { |number| met_by?(number) or other.met_by?(number) }
+ end
+end
+
+class TypeFilter
+ def initialize(filter)
+ if filter == :integer
+ @filter = Proc.new { |number| number.is_a? Integer }
+ elsif filter == :real
+ @filter = Proc.new do |number|
+ (number.is_a? Float) or (number.is_a? Rational)
+ end
+ elsif filter == :complex
+ @filter = Proc.new { |number| number.is_a? Complex }
+ end
+ end
+
+ def met_by?(number)
+ @filter.call(number)
+ end
+
+ def &(other)
+ Filter.new { |number| met_by?(number) and other.met_by?(number) }
+ end
+
+ def |(other)
+ Filter.new { |number| met_by?(number) or other.met_by?(number) }
+ end
+end
Здрасти,
Имам няколко коментара по кода ти:
- Имаш три метода, които си приличат адски много. Крещи за някакъв тип reuse. :))
- Погледни
Enumerable#each_with_object
и помисли дали може да ти е полезно. -
count == 0 ? true : false
. По добър начин да напишеш това? -
... if all? { |number| number != other }
. За това има по-кратък вариант. Помисли какво проверяваш и прегледай документацията наArray
. - Прегледай методите
Array#size
иArray#count
. В какво се различават? Кой би предпочел?