Evgenii Legotckoi
Evgenii LegotckoiAug. 26, 2016, 3:52 a.m.

User Guide #27 - Ruby - Object initialization

Our Fruit class from the previous chapter had two instance variables, one to describe the kind of fruit and another to describe its condition. It was only after writing a custom

inspect
method for the class that we realized it didn't make sense for a piece of fruit to lack those characteristics. Fortunately, ruby provides a way to ensure that instance variables always get initialized.

The
initialize
method

Whenever Ruby creates a new object, it looks for a method named

initialize
and executes it. So one simple thing we can do is use an
initialize
method to put default values into all the instance variables, so the
inspect
method will have something to say.

ruby> **class Fruit**
    |**def initialize**
    |**@kind = "apple"**
    |**@condition = "ripe"**
    |**end**
    | **end**
**nil**
ruby> **f4 = Fruit.new**
**"a ripe apple"**

Changing assumptions to requirements

There will be times when a default value doesn't make a lot of sense. Is there such a thing as a default kind of fruit? It may be preferable to require that each piece of fruit have its kind specified at the time of its creation. To do this, we would add a formal argument to the

initialize
method. For reasons we won't get into here, arguments you supply to
new
are actually delivered to
initialize
.

ruby> **class Fruit**
    |**def initialize( k )**
    |**@kind = k**
    |**@condition = "ripe"**
    |**end**
    | **end**
**nil**
ruby> **f5 = Fruit.new "mango"**
**"a ripe mango"**
ruby> **f6 = Fruit.new**
**ERR: (eval):1:in `initialize': wrong # of arguments(0 for 1)**

Flexible initialization

Above we see that once an argument is associated with the

initialize
method, it can't be left off without generating an error. If we want to be more considerate, we can use the argument if it is given, or fall back to default values otherwise.

ruby> **class Fruit**
    |**def initialize( k="apple" )**
    |**@kind = k**
    |**@condition = "ripe"**
    |**end**
    | **end**
**nil**
ruby> **f5 = Fruit.new "mango"**
**"a ripe mango"**
ruby> **f6 = Fruit.new**
**"a ripe apple"**

You can use default argument values for any method, not just

initialize
. The argument list must be arranged so that those with default values come last.

Sometimes it is useful to provide several ways to initialize an object. Although it is outside the scope of this tutorial, ruby supports object reflection and variable-length argument lists, which together effectively allow method overloading.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 2:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 8:19 a.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 7:51 a.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 11:02 a.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 3:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 6:04 a.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 3:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 9:10 a.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks