> For the complete documentation index, see [llms.txt](https://evgenii-afanasev.gitbook.io/ruby-course/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://evgenii-afanasev.gitbook.io/ruby-course/9_professional/2_struct.md).

# Структура

В пролшом уроке мы поняли, что создавая новый класс мы создаем экземпляр класса `Class`, но это не единственный способ создать такой экземпляр. `Struct` позволяем нам создать новый класс прямо во время выполнения нашей программы.

```ruby
# Каждый символ в аргументах это новая переменная
Person = Struct.new(:name, :age, :address)
person = Person.new('John', 23, 'Moscow')
p person # Person(name = John, age = 23, address = Moscow)
puts person.age # 23
```

Помимо создания переменных мы можем также создавать и методы, инициализируя их в блоке кода

```ruby
Person = Struct.new(:name, :age, :address) do
  def get_full_info
    "I'm #{name}, #{age} y.o. I'm from #{address}"  
  end
end
person = Person.new('John', 23, 'Moscow')
puts person.get_full_info # I'm John, 23 y.o. I'm from Moscow
```

Мы также можем наследоваться от структуры

```ruby
# В данном случае объект Struct заменяет конструктор у класса
class Person < Struct.new(:name, :age, :address)
  def get_full_info
    "I'm #{name}, #{age} y.o. I'm from #{address}"  
  end
end
```

Но все таки не следует делать такое наследование в реальной практике, так как есть аспекты, которые нарушают принципы ООП:

* при создании объекта нашего класса необязательно передавать все аргументы
* Все атрибуты нашего класса будут иметь `public` доступ

В основном структуры понадобятся, когда необходимо создать временный класс, который не будет использоваться в других местах программы.

## Дополнительный материал

* [Еще немного о Struct](https://www.paweldabrowski.com/articles/ruby-struct)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://evgenii-afanasev.gitbook.io/ruby-course/9_professional/2_struct.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
