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 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,441 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,441 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.