feat: implement ArrayProcessor class with chunk, include?, reduce, member?, and filter methods; add tests and documentation

lab3
Artem-Darius Weber 1 month ago
parent 205b10ff9d
commit 820a41173c

@ -0,0 +1,2 @@
source "https://rubygems.org"
gem "minitest", "~> 5.15"

@ -0,0 +1,13 @@
# Run
### Run example
```bash
ruby ./main.rb
```
### Run test
```bash
ruby test/test_array_processor.rb
```

@ -0,0 +1,67 @@
class ArrayProcessor
def initialize(array)
@array = array.dup.freeze
end
# Возвращает элементы массива
def elements
@array
end
# группировка элементов
def chunk
raise "No block given" unless block_given?
result = []
current_group = []
@array.each do |element|
if current_group.empty? || yield(element) == yield(current_group.last)
current_group << element
else
result << current_group
current_group = [element]
end
end
result << current_group unless current_group.empty?
result
end
# проверка наличия элемента
def include?(value)
@array.each do |element|
return true if element == value
end
false
end
# свёртка массива
def reduce(initial = nil)
raise "No block given" unless block_given?
accumulator = initial
@array.each do |element|
if accumulator.nil?
accumulator = element
else
accumulator = yield(accumulator, element)
end
end
accumulator
end
# проверка членства
def member?(value)
include?(value)
end
# фильтрация массива
def filter
raise "No block given" unless block_given?
result = []
@array.each do |element|
result << element if yield(element)
end
result
end
end

@ -0,0 +1,23 @@
require_relative 'lib/array_processor'
processor = ArrayProcessor.new([1, 2, 3, 4, 5, 6, 7, 8, 9])
# chunk
puts "Chunk example:"
p processor.chunk { |x| x.even? }
# include?
puts "Include example (5): #{processor.include?(5)}"
puts "Include example (10): #{processor.include?(10)}"
# reduce
puts "Reduce example (sum): #{processor.reduce(0) { |acc, x| acc + x }}"
# member?
puts "Member example (5): #{processor.member?(5)}"
puts "Member example (10): #{processor.member?(10)}"
# filter
puts "Filter example (odd numbers):"
p processor.filter { |x| x.odd? }

@ -0,0 +1,34 @@
require 'minitest/autorun'
require_relative '../lib/array_processor'
class ArrayProcessorTest < Minitest::Test
def setup
@processor = ArrayProcessor.new([1, 2, 3, 4, 5, 6, 7, 8, 9])
end
def test_chunk
result = @processor.chunk { |x| x.even? }
assert_equal [[1], [2], [3], [4], [5], [6], [7], [8], [9]], result
end
def test_include
assert_equal true, @processor.include?(5)
assert_equal false, @processor.include?(10)
end
def test_reduce
assert_equal 45, @processor.reduce(0) { |acc, x| acc + x }
assert_equal 120, @processor.reduce(1) { |acc, x| acc * x }
end
def test_member
assert_equal true, @processor.member?(5)
assert_equal false, @processor.member?(10)
end
def test_filter
result = @processor.filter { |x| x.odd? }
assert_equal [1, 3, 5, 7, 9], result
end
end
Loading…
Cancel
Save