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

User Guide #26 - Ruby - Accessors

What is an accessor?

We briefly discussed instance variables in an earlier chapter, but haven't done much with them yet. An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors . We'll see in a moment that we don't always have to write accessor methods explicitly, but let's go through all the motions for now. The two kinds of accessors are writers and readers .

ruby> **class Fruit**
    |**def set_kind(k)  # a writer**
    |**@kind = k**
    |**end**
    |**def get_kind     # a reader**
    |**@kind**
    |**end**
    | **end**
**nil**
ruby> **f1 = Fruit.new**
**#<Fruit:0xfd7e7c8c>**
ruby> **f1.set_kind("peach")  # use the writer**
**"peach"**
ruby> **f1.get_kind           # use the reader**
**"peach"**
ruby> **f1                    # inspect the object**
**#<Fruit:0xfd7e7c8c @kind="peach">**

Simple enough; we can store and retrieve information about what kind of fruit we're looking at. But our method names are a little wordy. The following is more concise, and more conventional:

ruby> **class Fruit**
    |**def kind=(k)**
    |**@kind = k**
    |**end**
    |**def kind**
    |**@kind**
    |**end**
    | **end**
**nil**
ruby> **f2 = Fruit.new**
**#<Fruit:0xfd7e7c8c>**
ruby> **f2.kind = "banana"**
**"banana"**
ruby> **f2.kind**
**"banana"**

The
inspect
method

A short digression is in order. You've noticed by now that when we try to look at an object directly, we are shown something cryptic like

#<anObject:0x83678>
. This is just a default behavior, and we are free to change it. All we need to do is add a method named
inspect
. It should return a string that describes the object in some sensible way, including the states of some or all of its instance variables.

ruby> **class Fruit**
    |**def inspect**
    |**"a fruit of the " + @kind + " variety"**
    |**end**
    | **end**
**nil**
ruby> **f2**
**"a fruit of the banana variety"**

A related method is

to_s
(convert to string), which is used when printing an object. In general, you can think of
inspect
as a tool for when you are writing and debugging programs, and
to_s
as a way of refining program output.
eval.rb
uses
inspect
whenever it displays results. You can use the
p
method to easily get debugging output from programs.

# Эти две строки эквивалентны:
p anObject
print anObject.inspect, "\n"

Making accessors the easy way

Since many instance variables need accessor methods, Ruby provides convenient shortcuts for the standard forms.

| Shortcut | Effect |
|

attr_reader :v
|
def v; @v; end
|
|
attr_writer :v
|
def v=(value); @v=value; end
|
|
attr_accessor :v
|
attr_reader :v; attr_writer :v
|
|
attr_accessor :v, :w
|
attr_accessor :v; attr_accessor :w
|

Let's take advantage of this and add freshness information. First we ask for an automatically generated reader and writer, and then we incorporate the new information into

inspect
:

ruby> **class Fruit**
    |**attr_accessor :condition**
    |**def inspect**
    |**"a " + @condition + @kind"**
    |**end**
    | **end**
**nil**
ruby> **f2.condition = "ripe"**
**"ripe"**
ruby> **f2**
**"a ripe banana"**

More fun with fruit

If nobody eats our ripe fruit, perhaps we should let time take its toll.

ruby> **class Fruit**
    |**def time_passes**
    |**@condition = "rotting"**
    |**end**
    | **end**
**nil**
ruby> **f2**
**"a ripe banana"**
ruby> **f2.time_passes**
**"rotting"**
ruby> **f2**
**"a rotting banana"**

But while playing around here, we have introduced a small problem. What happens if we try to create a third piece of fruit now? Remember that instance variables don't exist until values are assigned to them.

ruby> **f3 = Fruit.new**
**ERR: failed to convert nil into String**

It is the

inspect
method that is complaining here, and with good reason. We have asked it to report on the kind and condition of a piece of fruit, but as yet
f3
has not been assigned either attribute. If we wanted to, we could rewrite the
inspect
method so it tests instance variables using the
defined?
method and then only reports on them if they exist, but maybe that's not very useful; since every piece of fruit has a kind and condition, it seems we should make sure those always get defined somehow. That is the topic of the next chapter.

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
ИМ
Игорь МаксимовNov. 22, 2024, 10:51 p.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiNov. 1, 2024, 12:37 a.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 6:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 5:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 9:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
m
moogoNov. 22, 2024, 6:17 p.m.
Mosquito Spray System Effective Mosquito Systems for Backyard | Eco-Friendly Misting Control Device & Repellent Spray - Moogo ; Upgrade your backyard with our mosquito-repellent device! Our misters conce…
Evgenii Legotckoi
Evgenii LegotckoiJune 25, 2024, 1:11 a.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 5:04 p.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 1:49 p.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…

Follow us in social networks