+ 2

Excuse me, can anyone explain more about accessor in Ruby language? I still confuse about it

The one who wants to be a creator game

23rd Dec 2016, 10:56 PM
Andre Prastiyo
Andre Prastiyo - avatar
3 Respuestas
+ 2
It all revolves around the OOP part of ruby. In order to mantain some control over the access and usage of any attribute inside our ruby object, we must define if this attribute can be read or assigned outside of our object. That's where our attr_reader, attr_writer and attr_accessor come into play. Lets say we have an object called bycicle, and this object has a no_of_wheels attribute, if we want to be able to read this attribute outside the object, we wirte attr_reader :no_of_wheels If instead, we want to be able to assign this attribute outside of the object, we use attr_writer :no_of_wheels Lastly, if we want to be able to both read and write this attribute, we type attr_accessor :no_of_wheels This is basically a handy notation for quickly creating the getters and setters for each attribute inside your object
29th Dec 2016, 6:17 AM
Alejandro Aristizabal
Alejandro Aristizabal - avatar
+ 2
That's simple! Consider a simple var a: a = 5 This variable can be read b = a #read var a and assign it to b and written a = 7 #change value of a, from 5 to 7. you can deny or allow this actions for any attribute using the attribute accessors we talked about earlier. This is useful when you want to force your program to access the attributes the way you meant it to... For example: you have a player object, you don't want to be able to accidentaly assign the player's health without using methods like attack or gain-health, so you'll make your health attribute read only. Or you want to have an attribute that only the player can access, like his inventory, so this attribute would not be readable. Remember, this accessors define how the rest of your program can interact with the given attribute, the object in which they exist can manipulate the attribute just like a variable. Hope this helps!
29th Dec 2016, 2:43 PM
Alejandro Aristizabal
Alejandro Aristizabal - avatar
0
Thank you very much :) Your explaination is really helpful, but I what the difference between read-only attribute and assign-only attribute?
29th Dec 2016, 9:11 AM
Andre Prastiyo
Andre Prastiyo - avatar