0
0
Rubyprogramming~10 mins

Attr_reader, attr_writer, attr_accessor in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a read-only attribute for :name.

Ruby
class Person
  [1] :name
end
Drag options to blanks, or click blank then click option'
Aattr_writer
Battr_reader
Cattr_accessor
Dattr_private
Attempts:
3 left
💡 Hint
Common Mistakes
Using attr_writer instead of attr_reader will create write-only attribute.
Using attr_accessor creates both getter and setter.
2fill in blank
medium

Complete the code to create a write-only attribute for :password.

Ruby
class User
  [1] :password
end
Drag options to blanks, or click blank then click option'
Aattr_writer
Battr_reader
Cattr_accessor
Dattr_private
Attempts:
3 left
💡 Hint
Common Mistakes
Using attr_reader will create read-only attribute, not write-only.
attr_accessor creates both getter and setter.
3fill in blank
hard

Fix the error in the code to allow reading and writing for :email.

Ruby
class Contact
  [1] :email
end
Drag options to blanks, or click blank then click option'
Aattr_reader
Battr_writer
Cattr_private
Dattr_accessor
Attempts:
3 left
💡 Hint
Common Mistakes
Using attr_reader or attr_writer alone will not allow both reading and writing.
4fill in blank
hard

Fill both blanks to create a class with read-only :title and write-only :secret attributes.

Ruby
class Document
  [1] :title
  [2] :secret
end
Drag options to blanks, or click blank then click option'
Aattr_reader
Battr_writer
Cattr_accessor
Dattr_private
Attempts:
3 left
💡 Hint
Common Mistakes
Using attr_accessor for both will allow both reading and writing.
Mixing up attr_reader and attr_writer.
5fill in blank
hard

Fill all three blanks to create a class with read-write :name, read-only :age, and write-only :password.

Ruby
class Account
  [1] :name
  [2] :age
  [3] :password
end
Drag options to blanks, or click blank then click option'
Aattr_reader
Battr_writer
Cattr_accessor
Dattr_private
Attempts:
3 left
💡 Hint
Common Mistakes
Using attr_reader or attr_writer incorrectly for attributes needing both read and write.
Using attr_private which is not a valid Ruby method.