Envision, Create, Share

Welcome to HBGames, a leading amateur game development forum and Discord server. All are welcome, and amongst our ranks you will find experts in their field from all aspects of video game design and development.

attr_reader and attr_accessor

What do they do, exactly? And how can they help you in script-making? And can anybody give an example of each? I saw the Condtional Branch: Items where somebody used attr_reader to allow a conditional branch of having a certain quantity of an item with one line of script, without using an in-game variable to do so, and I thought that was kinda neat.
 
attr_accessor means that variables in that class preceded by the @ symbol can be accessed by other classes. i.e. if you have the variable @chicken in $game_map, you can see change the value of that variable is by using $game_map.chicken.

attr_reader does the same thing except it's like a "read-only" variable. You can't change it, just see the value of it.
 
And also their is attr_writer, so let's say you put "attr_writer: something" in $game_system. Then you could write to it using "$game_system.something += 1", but you could not read it by using "var = $game_system.something".

attr_accessor, attr_reader, and attr_writer just create access methods.

attr_reader creates this method:
Code:
def var
  return @var
end

attr_writer creates this method:
Code:
def var=(val)
  @var = val
end

attr_accessor creates both.
 
You could pretty much use accessor for everything. There's no real disadvantage that I can think of, other than that you could edit a variable that you don't want to edit... but if you don't want that to happen you could just use attr_accessor and just not edit it. :P
 
Oh, thanks for that! I once guessed that attr_reader will read and attr_accessor will write (so I used both whenever I need to access and change value of an attribute), but now I see that attr_accessor does both read and write.
 

Thank you for viewing

HBGames is a leading amateur video game development forum and Discord server open to all ability levels. Feel free to have a nosey around!

Discord

Join our growing and active Discord server to discuss all aspects of game making in a relaxed environment. Join Us

Content

  • Our Games
  • Games in Development
  • Emoji by Twemoji.
    Top