Evgenii Legotckoi
Aug. 26, 2016, 1:52 p.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

  1. 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
  1. initialize
method

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

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

  1. ruby> **class Fruit**
  2.     |**def initialize**
  3.     |**@kind = "apple"**
  4.     |**@condition = "ripe"**
  5.     |**end**
  6.     | **end**
  7. **nil**
  8. ruby> **f4 = Fruit.new**
  9. **"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

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

  1. ruby> **class Fruit**
  2.     |**def initialize( k )**
  3.     |**@kind = k**
  4.     |**@condition = "ripe"**
  5.     |**end**
  6.     | **end**
  7. **nil**
  8. ruby> **f5 = Fruit.new "mango"**
  9. **"a ripe mango"**
  10. ruby> **f6 = Fruit.new**
  11. **ERR: (eval):1:in `initialize': wrong # of arguments(0 for 1)**

Flexible initialization

Above we see that once an argument is associated with the

  1. 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.

  1. ruby> **class Fruit**
  2.     |**def initialize( k="apple" )**
  3.     |**@kind = k**
  4.     |**@condition = "ripe"**
  5.     |**end**
  6.     | **end**
  7. **nil**
  8. ruby> **f5 = Fruit.new "mango"**
  9. **"a ripe mango"**
  10. ruby> **f6 = Fruit.new**
  11. **"a ripe apple"**

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

  1. 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.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    April 16, 2025, 5:08 p.m.
    Благодарю за отзыв. И вам желаю всяческих успехов!
  • IscanderChe
    April 12, 2025, 5:12 p.m.
    Добрый день. Спасибо Вам за этот проект и отдельно за ответы на форуме, которые мне очень помогли в некоммерческих пет-проектах. Профессиональным программистом я так и не стал, но узнал мно…
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…