0
0
Rubyprogramming~30 mins

Attr_reader, attr_writer, attr_accessor in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Using attr_reader, attr_writer, and attr_accessor in Ruby
📖 Scenario: Imagine you are creating a simple program to manage a book's information in a library system. You want to control how the book's title and author can be accessed and changed.
🎯 Goal: Build a Ruby class Book that uses attr_reader, attr_writer, and attr_accessor to manage the book's title and author attributes properly.
📋 What You'll Learn
Create a class called Book with two instance variables: @title and @author.
Use attr_reader to allow reading the title only.
Use attr_writer to allow writing (changing) the author only.
Use attr_accessor to allow both reading and writing for a new attribute publisher.
Create an instance of Book with initial values for title, author, and publisher.
Print the title, change the author, change the publisher, and print all updated values.
💡 Why This Matters
🌍 Real World
Using <code>attr_reader</code>, <code>attr_writer</code>, and <code>attr_accessor</code> helps control how data inside objects can be accessed or changed, which is important in real software to keep data safe and consistent.
💼 Career
Many Ruby jobs require understanding how to use these accessors to write clean, maintainable code that protects object data and follows good design principles.
Progress0 / 4 steps
1
Create the Book class with instance variables
Create a class called Book with an initialize method that sets @title to "Ruby Basics" and @author to "Jane Doe".
Ruby
Need a hint?

Use class Book and define initialize with @title and @author set to the exact strings.

2
Add attr_reader and attr_writer for title and author
Add attr_reader :title to allow reading the title and attr_writer :author to allow changing the author.
Ruby
Need a hint?

Use attr_reader :title and attr_writer :author inside the class but outside any method.

3
Add attr_accessor for publisher and initialize it
Add attr_accessor :publisher to the class and update the initialize method to set @publisher to "Tech Books Publishing".
Ruby
Need a hint?

Add attr_accessor :publisher and set @publisher in initialize.

4
Create a Book instance and use the accessors
Create a variable book as a new Book instance. Print the title using book.title. Change the author to "John Smith" using book.author=. Change the publisher to "New Publisher" using book.publisher=. Finally, print the updated author and publisher using puts.
Ruby
Need a hint?

Create the book object, print title, update author and publisher, then print updated values.