Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby Ruby Objects and Classes Variables and Methods Attribute Readers

Andrew Carr
Andrew Carr
10,979 Points

attr_reader question

I'm a bit confused on how ruby makes the jump of replacing a function

def [method] ;
   '@arg1' ;
end 

to

just attr_reader :arg1

In the first, you have the option of naming your method whatever you want. And while the examples usually read

def ['method_name'];
 @'methodname' ;
end

It seems a bit of a jump to use att_reader to make that assumption that your method matches the argument name.

Can anyone clarify this for me? Apologies if the logic seems a bit off, but I'm confused on what would seem like a potentially hazardous jump in code. Feel free to ask me to clarify.

Best, Andrew Carr

Sryz for the odd formatting. I put in the semi-colons to show end of lines since the text viewer changes my original input's formatting.

Maciej Czuchnowski
Maciej Czuchnowski
36,440 Points

I edited your question to make the code appear as it should. Click edit to see what I did exactly.

1 Answer

Maciej Czuchnowski
Maciej Czuchnowski
36,440 Points

Maybe this explanation will help you: http://stackoverflow.com/questions/5046831/why-use-rubys-attr-accessor-attr-reader-and-attr-writer

If this is not what you were asking about, please let me know. Basically, the attr_ thing, behind the scenes, defines one or two methods for you (for reading the value of an instance variable named the same as the method and/or for changing the value of the said variable), so you don't have to write them on your own.