0
0
Rubyprogramming~5 mins

Attr_reader, attr_writer, attr_accessor in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does attr_reader do in Ruby?

attr_reader creates a getter method for an instance variable. It lets you read the value but not change it directly.

Click to reveal answer
beginner
What is the purpose of attr_writer in Ruby?

attr_writer creates a setter method for an instance variable. It lets you change the value but not read it directly.

Click to reveal answer
beginner
Explain attr_accessor in Ruby.

attr_accessor creates both getter and setter methods for an instance variable. You can read and change the value.

Click to reveal answer
intermediate
Why use attr_reader, attr_writer, or attr_accessor instead of writing methods manually?

They save time and make code cleaner by automatically creating simple getter and setter methods.

Click to reveal answer
beginner
Given attr_reader :name, can you change the @name variable directly from outside the class?

No, attr_reader only allows reading the value. To change it, you need a setter method like attr_writer or attr_accessor.

Click to reveal answer
Which Ruby attribute method allows both reading and writing an instance variable?
Aattr_accessor
Battr_reader
Cattr_writer
Dattr_mutator
What does attr_writer :age provide?
AA method to read @age
BA method to write @age
CBoth read and write methods for @age
DNo methods for @age
If a class has only attr_reader :title, what happens if you try to assign obj.title = 'New'?
ARaises an error
BIt works fine
CIgnores the assignment
DCreates a new variable
Which of these is NOT a reason to use attr_accessor?
ATo reduce boilerplate code
BTo automatically create getter and setter
CTo make variables private
DTo simplify class design
What is the default visibility of methods created by attr_reader, attr_writer, and attr_accessor?
AModule
BProtected
CPrivate
DPublic
Describe the differences between attr_reader, attr_writer, and attr_accessor in Ruby.
Think about what each method lets you do with an instance variable.
You got /3 concepts.
    Explain why using attr_accessor can make your Ruby class code cleaner and easier to maintain.
    Consider how much code you save by not writing simple getter and setter methods.
    You got /3 concepts.