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