Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Objects and Classes Variables and Methods Attribute Writers and Accessors

Stupid question: What happens if you don't set an attr_reader, writer, or accessor?

Why do you need to use them? I am a bit confused. I tried watching the videos over again and I'm still lost. Could you please list a few examples as to when they'd be used, too? The lesson was a bit too fast paced because I have a low mental capacity.

1 Answer

Brandon Barrette
Brandon Barrette
20,485 Points

You'll get the following errors if trying to call user.name

For attr_reader, you get a NoMethodError "undefined method `name'" because the method you are calling can't be read, meaning like user.name is undefined. Attr_reader for name is equivalent to:

def name
  @name
end

For attr_writer, you get a NoMethodError "undefined method `name='". Notice here the equal sign because ruby is trying to write (or assign) to the instance variable name. Attr_writer is equivalent to:

def name=(value)
  @name = value
end

Attr_accessor is just combining attr_reader AND attr_writer. I always start defining them as attr_reader and attr_writer separately, then anywhere I see both an attr_reader and attr_writer, then I combine them to an attr_accessor.

Thank you! This is a nice and clear answer!