Compare commits
16 Commits
Author | SHA1 | Date |
---|---|---|
Artem-Darius Weber | e603842e7c | 2 days ago |
Artem-Darius Weber | d7c500f202 | 2 days ago |
Artem-Darius Weber | 8ccf7239f9 | 2 days ago |
Artem-Darius Weber | 6f9cd89526 | 4 days ago |
Artem-Darius Weber | b1d90eab30 | 4 days ago |
Artem-Darius Weber | 9032b20783 | 2 weeks ago |
Artem-Darius Weber | c9a56f66f4 | 1 month ago |
Artem-Darius Weber | 820a41173c | 1 month ago |
Artem-Darius Weber | 205b10ff9d | 1 month ago |
Artem-Darius Weber | f015f43c99 | 1 month ago |
Artem-Darius Weber | b9453a87e8 | 1 month ago |
Artem-Darius Weber | 988d9c83dd | 1 month ago |
Artem-Darius Weber | a50ef4122e | 1 month ago |
Artem-Darius Weber | 44e77f3679 | 1 month ago |
Artem-Darius Weber | 8a8d9cfdd8 | 1 month ago |
Artem-Darius Weber | 8d8cc46bde | 4 months ago |
@ -1,16 +0,0 @@
|
|||||||
require_relative '../src/02_user_interface.rb'
|
|
||||||
|
|
||||||
RSpec.describe "Main" do
|
|
||||||
before do
|
|
||||||
allow(STDIN).to receive(:gets).and_return("ruby\n")
|
|
||||||
end
|
|
||||||
|
|
||||||
it "greets the user and checks Ruby as language" do
|
|
||||||
expect { main() }.to output("Hello my catgirl test_user! \nWhat is your love language?\nruby\nc++\npy\nПодлиза \n").to_stdout
|
|
||||||
end
|
|
||||||
|
|
||||||
it "handles unknown language input" do
|
|
||||||
allow(STDIN).to receive(:gets).and_return("java\n")
|
|
||||||
expect { main() }.to output(/Неизвестный язык: java/).to_stdout
|
|
||||||
end
|
|
||||||
end
|
|
@ -1,2 +0,0 @@
|
|||||||
puts "Hello, world!"
|
|
||||||
|
|
@ -1,30 +0,0 @@
|
|||||||
#!/usr/bin/env ruby
|
|
||||||
|
|
||||||
LANGUAGES = [
|
|
||||||
"ruby",
|
|
||||||
"c++",
|
|
||||||
"py"
|
|
||||||
]
|
|
||||||
|
|
||||||
def main()
|
|
||||||
user_name = ARGV[0]
|
|
||||||
puts "Hello my catgirl #{user_name}! \nWhat is your love language?"
|
|
||||||
LANGUAGES.each { |language| puts "#{language}", " " }
|
|
||||||
|
|
||||||
user_lang = STDIN.gets.chomp
|
|
||||||
|
|
||||||
case user_lang
|
|
||||||
when "ruby"
|
|
||||||
puts "Подлиза \n"
|
|
||||||
when "c++"
|
|
||||||
puts "MATLAB скушал? \n"
|
|
||||||
when "TS/JS"
|
|
||||||
puts "Фронтендер, Фууу! \n"
|
|
||||||
when "py"
|
|
||||||
puts "Девопсер, иди ДАГИ писать \n"
|
|
||||||
else
|
|
||||||
puts "Неизвестный язык: #{user_lang}"
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
main()
|
|
@ -1,39 +0,0 @@
|
|||||||
#!/usr/bin/env ruby
|
|
||||||
|
|
||||||
LANGUAGES = [
|
|
||||||
"ruby",
|
|
||||||
"c++",
|
|
||||||
"py"
|
|
||||||
]
|
|
||||||
|
|
||||||
def main()
|
|
||||||
user_name = ARGV[0]
|
|
||||||
puts "Hello my catgirl #{user_name}! \nWhat is your love language?"
|
|
||||||
LANGUAGES.each { |language| puts "#{language}", " " }
|
|
||||||
|
|
||||||
user_lang = STDIN.gets.chomp
|
|
||||||
case user_lang
|
|
||||||
when "ruby"
|
|
||||||
puts "Подлиза \n"
|
|
||||||
when "c++"
|
|
||||||
puts "MATLAB скушал? \n"
|
|
||||||
when "TS/JS"
|
|
||||||
puts "Фронтендер, Фууу! \n"
|
|
||||||
when "py"
|
|
||||||
puts "Девопсер, иди ДАГИ писать \n"
|
|
||||||
end
|
|
||||||
|
|
||||||
puts "Введите команду на языке Ruby для выполнения:"
|
|
||||||
ruby_command = STDIN.gets.chomp
|
|
||||||
begin
|
|
||||||
eval(ruby_command)
|
|
||||||
rescue Exception => e
|
|
||||||
puts "Ошибка выполнения команды Ruby: #{e.message}"
|
|
||||||
end
|
|
||||||
|
|
||||||
puts "Введите команду операционной системы для выполнения:"
|
|
||||||
os_command = STDIN.gets.chomp
|
|
||||||
system(os_command)
|
|
||||||
end
|
|
||||||
|
|
||||||
main()
|
|
@ -1,68 +0,0 @@
|
|||||||
|
|
||||||
|
|
||||||
def find_min_element_for(arr)
|
|
||||||
min_element = arr[0]
|
|
||||||
for element in arr
|
|
||||||
min_element = element if element < min_element
|
|
||||||
end
|
|
||||||
min_element
|
|
||||||
end
|
|
||||||
|
|
||||||
|
|
||||||
def find_min_element_while(arr)
|
|
||||||
min_element = arr[0]
|
|
||||||
index = 0
|
|
||||||
while index < arr.size
|
|
||||||
min_element = arr[index] if arr[index] < min_element
|
|
||||||
index += 1
|
|
||||||
end
|
|
||||||
min_element
|
|
||||||
end
|
|
||||||
|
|
||||||
|
|
||||||
def find_first_positive_index_for(arr)
|
|
||||||
for index in 0...arr.size
|
|
||||||
return index if arr[index] > 0
|
|
||||||
end
|
|
||||||
nil
|
|
||||||
end
|
|
||||||
|
|
||||||
|
|
||||||
def find_first_positive_index_while(arr)
|
|
||||||
index = 0
|
|
||||||
while index < arr.size
|
|
||||||
return index if arr[index] > 0
|
|
||||||
index += 1
|
|
||||||
end
|
|
||||||
nil
|
|
||||||
end
|
|
||||||
|
|
||||||
|
|
||||||
def find_first_positive_for(arr)
|
|
||||||
for element in arr
|
|
||||||
return element if element > 0
|
|
||||||
end
|
|
||||||
nil
|
|
||||||
end
|
|
||||||
|
|
||||||
|
|
||||||
def find_first_positive_while(arr)
|
|
||||||
index = 0
|
|
||||||
while index < arr.size
|
|
||||||
return arr[index] if arr[index] > 0
|
|
||||||
index += 1
|
|
||||||
end
|
|
||||||
nil
|
|
||||||
end
|
|
||||||
|
|
||||||
# INPUT
|
|
||||||
array = [-10, -5, 0, 3, 5, -2]
|
|
||||||
|
|
||||||
puts "Минимальный элемент (for): #{find_min_element_for(array)}"
|
|
||||||
puts "Минимальный элемент (while): #{find_min_element_while(array)}"
|
|
||||||
|
|
||||||
puts "Индекс первого положительного элемента (for): #{find_first_positive_index_for(array)}"
|
|
||||||
puts "Индекс первого положительного элемента (while): #{find_first_positive_index_while(array)}"
|
|
||||||
|
|
||||||
puts "Первый положительный элемент (for): #{find_first_positive_for(array)}"
|
|
||||||
puts "Первый положительный элемент (while): #{find_first_positive_while(array)}"
|
|
@ -1,62 +0,0 @@
|
|||||||
|
|
||||||
|
|
||||||
def find_min_element(arr)
|
|
||||||
min_element = arr[0]
|
|
||||||
arr.each do |element|
|
|
||||||
min_element = element if element < min_element
|
|
||||||
end
|
|
||||||
min_element
|
|
||||||
end
|
|
||||||
|
|
||||||
|
|
||||||
def find_first_positive_index(arr)
|
|
||||||
arr.each_with_index do |element, index|
|
|
||||||
return index if element > 0
|
|
||||||
end
|
|
||||||
nil
|
|
||||||
end
|
|
||||||
|
|
||||||
|
|
||||||
def find_first_positive(arr)
|
|
||||||
arr.each do |element|
|
|
||||||
return element if element > 0
|
|
||||||
end
|
|
||||||
nil
|
|
||||||
end
|
|
||||||
|
|
||||||
|
|
||||||
def main
|
|
||||||
method_name = ARGV[0]
|
|
||||||
file_path = ARGV[1]
|
|
||||||
|
|
||||||
if method_name.nil? || file_path.nil?
|
|
||||||
puts "Неправльный формат ввода. Использование: ruby program.rb <method_name> <file_path>"
|
|
||||||
puts "method_name: 'min', 'first_positive_index' или 'first_positive'"
|
|
||||||
exit
|
|
||||||
end
|
|
||||||
|
|
||||||
begin
|
|
||||||
array = File.read(file_path).split.map(&:to_i)
|
|
||||||
rescue Errno::ENOENT
|
|
||||||
puts "Файл не найден: #{file_path}"
|
|
||||||
exit
|
|
||||||
end
|
|
||||||
|
|
||||||
case method_name
|
|
||||||
when 'min'
|
|
||||||
result = find_min_element(array)
|
|
||||||
puts "Минимальный элемент: #{result}"
|
|
||||||
when 'first_positive_index'
|
|
||||||
result = find_first_positive_index(array)
|
|
||||||
puts "Индекс первого положительного элемента: #{result.nil? ? 'Нет положительного элемента' : result}"
|
|
||||||
when 'first_positive'
|
|
||||||
result = find_first_positive(array)
|
|
||||||
puts "Первый положительный элемент: #{result.nil? ? 'Нет положительного элемента' : result}"
|
|
||||||
else
|
|
||||||
puts "Неизвестный метод: #{method_name}"
|
|
||||||
puts "Доступные методы: 'min', 'first_positive_index', 'first_positive'"
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
|
|
||||||
main if __FILE__ == $0
|
|
@ -1 +0,0 @@
|
|||||||
-10 -5 0 3 5 -2
|
|
@ -1,4 +0,0 @@
|
|||||||
# Lab 2
|
|
||||||
|
|
||||||
> "И тут я обнаружил что случайно сделал 3-5 задачи в 1-2"
|
|
||||||
|
|
@ -1,92 +0,0 @@
|
|||||||
require_relative 'person'
|
|
||||||
|
|
||||||
class Student < Person
|
|
||||||
attr_accessor :surname, :name, :patronymic
|
|
||||||
|
|
||||||
def initialize(args = {})
|
|
||||||
super(args)
|
|
||||||
@surname = args.fetch(:surname)
|
|
||||||
raise ArgumentError, "Invalid surname format: #{@surname}" unless self.class.valid_name?(@surname)
|
|
||||||
|
|
||||||
@name = args.fetch(:name)
|
|
||||||
raise ArgumentError, "Invalid name format: #{@name}" unless self.class.valid_name?(@name)
|
|
||||||
|
|
||||||
@patronymic = args.fetch(:patronymic)
|
|
||||||
raise ArgumentError, "Invalid patronymic format: #{@patronymic}" unless self.class.valid_name?(@patronymic)
|
|
||||||
|
|
||||||
set_contacts(
|
|
||||||
phone: args[:phone],
|
|
||||||
telegram: args[:telegram],
|
|
||||||
email: args[:email]
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
def self.from_string(student_string)
|
|
||||||
parts = student_string.split('|').map(&:strip)
|
|
||||||
surname, name, patronymic = parts[0].split(' ')
|
|
||||||
id = parts[1].split(': ').last.to_i
|
|
||||||
phone = parts[2].split(': ').last
|
|
||||||
telegram = parts[3].split(': ').last
|
|
||||||
email = parts[4].split(': ').last
|
|
||||||
git = parts[5].split(': ').last
|
|
||||||
|
|
||||||
new(
|
|
||||||
surname: surname,
|
|
||||||
name: name,
|
|
||||||
patronymic: patronymic,
|
|
||||||
id: id,
|
|
||||||
phone: phone,
|
|
||||||
telegram: telegram,
|
|
||||||
email: email,
|
|
||||||
git: git
|
|
||||||
)
|
|
||||||
end
|
|
||||||
|
|
||||||
def self.read_from_txt(file_path)
|
|
||||||
raise IOError, "File path is invalid or file does not exist: #{file_path}" unless File.exist?(file_path)
|
|
||||||
|
|
||||||
students = []
|
|
||||||
|
|
||||||
File.foreach(file_path) do |line|
|
|
||||||
line.strip!
|
|
||||||
next if line.empty?
|
|
||||||
|
|
||||||
begin
|
|
||||||
student = from_string(line)
|
|
||||||
students << student
|
|
||||||
rescue ArgumentError => e
|
|
||||||
puts "Error processing line: '#{line}'. Reason: #{e.message}"
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
students
|
|
||||||
end
|
|
||||||
|
|
||||||
def self.write_to_txt(file_path, students)
|
|
||||||
raise ArgumentError, "Expected an array of Student objects" unless students.is_a?(Array) && students.all? { |s| s.is_a?(Student) }
|
|
||||||
|
|
||||||
File.open(file_path, 'w') do |file|
|
|
||||||
students.each do |student|
|
|
||||||
file.puts student.to_s
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
puts "Data successfully written to #{file_path}"
|
|
||||||
rescue IOError => e
|
|
||||||
puts "An error occurred while writing to the file: #{e.message}"
|
|
||||||
end
|
|
||||||
|
|
||||||
def surname_and_initials
|
|
||||||
"#{@surname} #{name[0]}.#{patronymic[0]}."
|
|
||||||
end
|
|
||||||
|
|
||||||
def to_s
|
|
||||||
"#{@surname} #{@name} #{@patronymic} | ID: #{@id || 'N/A'} | " \
|
|
||||||
"Phone: #{@phone || 'N/A'} | Telegram: #{@telegram || 'N/A'} | " \
|
|
||||||
"Email: #{@email || 'N/A'} | Git: #{@git || 'N/A'}"
|
|
||||||
end
|
|
||||||
|
|
||||||
def get_info
|
|
||||||
"#{surname_and_initials}, Git: #{git_info}, Contact: #{contact_info}"
|
|
||||||
end
|
|
||||||
end
|
|
@ -1,31 +0,0 @@
|
|||||||
require_relative 'person'
|
|
||||||
|
|
||||||
class StudentShort < Person
|
|
||||||
attr_reader :surname_initials, :contact
|
|
||||||
|
|
||||||
def initialize(student)
|
|
||||||
super(id: student.id, git: student.git_info)
|
|
||||||
@surname_initials = student.surname_and_initials
|
|
||||||
@contact = student.contact_info
|
|
||||||
end
|
|
||||||
|
|
||||||
def self.from_string(id, info_string)
|
|
||||||
parts = info_string.split(', ').map(&:strip)
|
|
||||||
surname_initials = parts[0]
|
|
||||||
git = parts[1].split(': ').last
|
|
||||||
contact = parts[2].split(': ').last
|
|
||||||
|
|
||||||
new_instance = allocate
|
|
||||||
new_instance.send(:initialize_from_data, id, surname_initials, git, contact)
|
|
||||||
new_instance
|
|
||||||
end
|
|
||||||
|
|
||||||
private
|
|
||||||
|
|
||||||
def initialize_from_data(id, surname_initials, git, contact)
|
|
||||||
@id = id
|
|
||||||
@surname_initials = surname_initials
|
|
||||||
@git = git
|
|
||||||
@contact = contact
|
|
||||||
end
|
|
||||||
end
|
|
@ -0,0 +1,2 @@
|
|||||||
|
source "https://rubygems.org"
|
||||||
|
gem "minitest", "~> 5.15"
|
@ -0,0 +1 @@
|
|||||||
|
5
|
@ -0,0 +1,27 @@
|
|||||||
|
# Run
|
||||||
|
|
||||||
|
### Run example
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ruby ./main.rb
|
||||||
|
```
|
||||||
|
|
||||||
|
### Run test
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ruby test/test_array_processor.rb
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
# Methods:
|
||||||
|
|
||||||
|
chunk - дробит массив на сущности по результату выполнения кода, even - четные число
|
||||||
|
|
||||||
|
include - содержит ли массив элемент
|
||||||
|
|
||||||
|
member - аналогично include
|
||||||
|
|
||||||
|
reduce - накапливает значения в аккумулияторе складывая все значения
|
||||||
|
|
||||||
|
filter - select элементов для который блок вернул true. odd - нечетное число
|
||||||
|
|
@ -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
|
@ -0,0 +1,118 @@
|
|||||||
|
require 'nokogiri'
|
||||||
|
|
||||||
|
class HtmlTree
|
||||||
|
include Enumerable
|
||||||
|
|
||||||
|
def initialize(html)
|
||||||
|
puts "Input HTML:\n#{html.inspect}"
|
||||||
|
@root = parse_html(html)
|
||||||
|
raise "Parsed HTML tree is empty" if @root.nil?
|
||||||
|
end
|
||||||
|
|
||||||
|
def each(order = :breadth_first, &block)
|
||||||
|
case order
|
||||||
|
when :breadth_first
|
||||||
|
breadth_first_traversal(&block)
|
||||||
|
when :depth_first
|
||||||
|
depth_first_traversal(&block)
|
||||||
|
else
|
||||||
|
raise ArgumentError, "Unknown order: #{order}"
|
||||||
|
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)
|
||||||
|
doc = Nokogiri::HTML::DocumentFragment.parse(html)
|
||||||
|
root_node = doc.at_css('body') || doc.children.find(&:element?) || doc.root
|
||||||
|
return nil if root_node.nil? || root_node.children.empty?
|
||||||
|
|
||||||
|
build_tree(root_node)
|
||||||
|
end
|
||||||
|
|
||||||
|
def build_tree(node)
|
||||||
|
if node.element?
|
||||||
|
children = node.children.map { |child| build_tree(child) }.compact
|
||||||
|
HtmlTag.new(node.name, node.attributes.transform_values(&:value), children)
|
||||||
|
elsif node.text? && !node.content.strip.empty?
|
||||||
|
HtmlTag.new("text", { "content" => node.content.strip }, [])
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def breadth_first_traversal
|
||||||
|
queue = [@root].compact
|
||||||
|
until queue.empty?
|
||||||
|
current = queue.shift
|
||||||
|
next if current.nil?
|
||||||
|
|
||||||
|
yield current
|
||||||
|
queue.concat(current.children.compact) if current.has_children?
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def depth_first_traversal(node = @root, &block)
|
||||||
|
return if node.nil?
|
||||||
|
|
||||||
|
yield node
|
||||||
|
node.children.compact.each { |child| depth_first_traversal(child, &block) } if node.has_children?
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
class HtmlTag
|
||||||
|
attr_reader :name, :attributes, :children
|
||||||
|
|
||||||
|
def initialize(name, attributes, children = [])
|
||||||
|
@name = name
|
||||||
|
@attributes = attributes
|
||||||
|
@children = children
|
||||||
|
end
|
||||||
|
|
||||||
|
def has_children?
|
||||||
|
!@children.empty?
|
||||||
|
end
|
||||||
|
|
||||||
|
def to_s
|
||||||
|
"#{@name} #{@attributes}"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
html = <<-HTML
|
||||||
|
<div id="root">
|
||||||
|
<p class="text">Hello, world!</p>
|
||||||
|
<ul>
|
||||||
|
<li>Item 1</li>
|
||||||
|
<li>Item 2</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
HTML
|
||||||
|
|
||||||
|
tree = HtmlTree.new(html)
|
||||||
|
|
||||||
|
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 }
|
||||||
|
|
||||||
|
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
|
@ -0,0 +1,30 @@
|
|||||||
|
|
||||||
|
numbers = [5, 3, 8, 1, 2]
|
||||||
|
|
||||||
|
# сортировка чисел
|
||||||
|
sorted_numbers = numbers.sort
|
||||||
|
puts "Sorted numbers using sort: #{sorted_numbers}"
|
||||||
|
|
||||||
|
# сортировка по алфавиту
|
||||||
|
words = ["apple", "orange", "banana", "grape"]
|
||||||
|
sorted_words = words.sort
|
||||||
|
puts "Sorted words using sort: #{sorted_words}"
|
||||||
|
|
||||||
|
people = [
|
||||||
|
{ name: "Alice", age: 30 },
|
||||||
|
{ name: "Bob", age: 25 },
|
||||||
|
{ name: "Charlie", age: 35 }
|
||||||
|
]
|
||||||
|
|
||||||
|
# сортировка по возрасту
|
||||||
|
sorted_people_by_age = people.sort { |a, b| a[:age] <=> b[:age] }
|
||||||
|
puts "Sorted people by age using sort: #{sorted_people_by_age}"
|
||||||
|
|
||||||
|
# сортировка по возрасту
|
||||||
|
sorted_people_by_age2 = people.sort_by { |person| person[:age] }
|
||||||
|
puts "Sorted people by age using sort_by: #{sorted_people_by_age2}"
|
||||||
|
|
||||||
|
# сортировка по длине строки
|
||||||
|
words = ["cat", "elephant", "dog", "hippopotamus"]
|
||||||
|
sorted_by_length = words.sort_by { |word| word.length }
|
||||||
|
puts "Sorted words by length using sort_by: #{sorted_by_length}"
|
Loading…
Reference in new issue