From 8ccf7239f94c12e2bd7e63824aa32aef842c8c22 Mon Sep 17 00:00:00 2001 From: Artem Darius Weber Date: Wed, 8 Jan 2025 08:43:22 +0300 Subject: [PATCH] feat: add select and reduce methods to HtmlTree class; update examples in main.rb --- lab3_task1_funcation_block_arg/main.rb | 2 +- lab3_task3_html_tree/main.rb | 27 ++++++++++++++++++++++++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/lab3_task1_funcation_block_arg/main.rb b/lab3_task1_funcation_block_arg/main.rb index 0f80877..a01cfb4 100644 --- a/lab3_task1_funcation_block_arg/main.rb +++ b/lab3_task1_funcation_block_arg/main.rb @@ -1,9 +1,9 @@ +# add examples for sort and sort)by def indices_sorted_by_descending_values(array) array.each_with_index.to_a .sort_by { |(element, index)| -element } .map { |(element, index)| index } - end diff --git a/lab3_task3_html_tree/main.rb b/lab3_task3_html_tree/main.rb index 053190f..525e1d8 100644 --- a/lab3_task3_html_tree/main.rb +++ b/lab3_task3_html_tree/main.rb @@ -4,7 +4,7 @@ class HtmlTree include Enumerable def initialize(html) - puts "Input HTML:\n#{html.inspect}" # Проверяем входной HTML + puts "Input HTML:\n#{html.inspect}" @root = parse_html(html) raise "Parsed HTML tree is empty" if @root.nil? end @@ -20,6 +20,21 @@ class HtmlTree end end + def select(order = :breadth_first, &block) + results = [] + each(order) do |node| + results << node if block.call(node) + end + results + end + + def reduce(accumulator = nil, order = :breadth_first, &block) + each(order) do |node| + accumulator = block.call(accumulator, node) + end + accumulator + end + private def parse_html(html) @@ -92,4 +107,12 @@ puts "Traversal in breadth-first order:" tree.each(:breadth_first) { |tag| puts tag } puts "\nTraversal in depth-first order:" -tree.each(:depth_first) { |tag| puts tag } \ No newline at end of file +tree.each(:depth_first) { |tag| puts tag } + +puts "Select tags with class 'text':" +selected_tags = tree.select { |tag| tag.attributes["class"] == "text" } +puts selected_tags + +puts "\nReduce example (concatenate all tag names):" +reduced_value = tree.reduce("") { |acc, tag| acc + " " + tag.name } +puts reduced_value.strip \ No newline at end of file