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, attr_writer and attr_accessor

Khoa

Member

Could some body please give me some examples about attr_reader, attr_writer and attr_accessor? I don't know what do they do and how to use them (><).
 
from: http://www.ruby-doc.org/core/classes/Mo ... ml#M001701
  attr(symbol, writable=false) => nil

Defines a named attribute for this module, where the name is symbol.id2name, creating an instance variable (@name) and a corresponding access method to read it. If the optional writable argument is true, also creates a method called name= to set the attribute.

  module Mod
    attr  :size, true
  end

is equivalent to:

  module Mod
    def size
      @size
    end
    def size=(val)
      @size = val
    end
  end

attr_accessor(symbol, ...) => nil

Equivalent to calling ``attrsymbol, true’’ on each symbol in turn.

  module Mod
    attr_accessor:)one, :two)
  end
  Mod.instance_methods.sort  #=> ["one", "one=", "two", "two="]

attr_reader(symbol, ...) => nil

Creates instance variables and corresponding methods that return the value of each instance variable. Equivalent to calling ``attr:name’’ on each name in turn.
attr_writer(symbol, ...) => nil

Creates an accessor method to allow assignment to the attribute aSymbol.id2name.
 

khmp

Sponsor

I find it helpful when coding to ask myself a ton of questions about what I'm trying to do. This applies to attributes as well. To decide which one you will need. You just need to ask yourself; Will I ever need to change the value from outside the class? Will I only ever just need to see the value from outside of this class? Will I need to do both from outside the class' definition?

Answering yes to the first one means that the value should have either an attr_writer written for it or a method like the one hanmac has just above.

Answering yes to the second one means that the value should have either an attr_reader written for it or a method like this:
Code:
attr_reader :value
...
def value
  return @value
end

And lastly answering yes to both questions means that you use an attr_accessor for the value or write out both methods of accessing and manipulating:
Code:
attr_accessor :value
...
def value
  return @value
end

def value=(value)
  @value = value
end

Hope that helps.

Good luck with it Khoa! :thumb:
 

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