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

Brent Forwood
Brent Forwood
18,999 Points

Method does not work, but attr_writer does

I'm just curious as to why, when I got to the part to change title.name, we first used this method:

def title=(new_title)
  @title = new_title
end

This returned the error:

Title: Mr.
name.rb:23:in <main>': private methodtitle=' called for #<Name:0x007f8bad0fc9c8> (NoMethodError)

When I got to the part where we deleted the method and inserted attr_writer :title, it worked fine. I cannot figure out what may have been wrong with th method. The above is exactly how I had it in the code.

Hi Brent,

In your code, you don't return any value, hence the "(NoMethodError)". Just add "return @title".

Here's an example: START def title(new_title) @title = new_title return @title end

title1 = title("Mr.") puts title1 END

What the attr_writer allows you to do is to overwrite title.name, so it is much simpler to use.

Hope it helped.

Brent Forwood
Brent Forwood
18,999 Points

Hey Francisco,

The thing is, what is typed up above is what was also instructed in the video. That was my main concern.

But thank you for the reply, and I will go back to the video when I get a chance and try that out. Adding the 'return' makes sense, and will most likely go back and try it when I get a chance.

1 Answer

Francisco's answer is incorrect. Your method (so long as something is passed in as an argument) would return the value of @title.

It's difficult to know for sure what happened in your code to cause the error without seeing it, but it looks like the method was private (underneath 'private' in a class), and you tried to call it from somewhere that can't get to it (basically anywhere outside of its class).

attr_writer :title

is the SAME as having

def title=(new_title)
  @title = new_title
end

Further reading:

http://stackoverflow.com/questions/5046831/why-use-rubys-attr-accessor-attr-reader-and-attr-writer

https://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/45-more-classes/lessons/110-instance-variables