|
|
|
@ -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)
|
|
|
|
@ -93,3 +108,11 @@ tree.each(:breadth_first) { |tag| puts tag }
|
|
|
|
|
|
|
|
|
|
puts "\nTraversal in depth-first order:"
|
|
|
|
|
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
|