feat: add select and reduce methods to HtmlTree class; update examples in main.rb

lab3
Artem-Darius Weber 1 day ago
parent 6f9cd89526
commit 8ccf7239f9

@ -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

@ -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 }
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
Loading…
Cancel
Save