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

Hossam Khalifa
Hossam Khalifa
17,200 Points

Attr_writer vs attr_reader

When setting an attr_reader it can be used within methods without the '@' symobl to get the value.

But when I try to set the value if something is set as an attr_writer the '@' must be used to set the value or it will not work. Example

 Class SomeThing
attr_accessor :name
 def initialize(name)
   @name = name
end
def getName?
  name # This will return the name
end

#but this will not set the name

def setName!(new_name)
   name = new_name
end

end

Can someone explain why Or tell me if I am mistaking Thank you Jason Seifer please answer

Jessica H
Jessica H
16,607 Points

By making @ variable, you are thus making name available throughout the class by other methods..

If you don't have an @ sign, the variable will only "local" and can only be used by the method in which you are defining it.

2 Answers

Brandon Barrette
Brandon Barrette
20,485 Points

Inside the initialize, from what I understand, you must use the @ since it's an instance variable (initializing an instance of the class). In other methods you write, you wouldn't need the @ if it's an attr_reader, attr_writer, or attr_accessor.

Hossam Khalifa
Hossam Khalifa
17,200 Points

I don't think you get me! It works with attr_reader But not with attr_writer My question is why??

Hossam Khalifa
Hossam Khalifa
17,200 Points

I don't think you get me! It works with attr_reader But not with attr_writer My question is why??

Jason Seifer
STAFF
Jason Seifer
Treehouse Guest Teacher

Hi Hossam Khalifa, great question!

When you do the attr_writer method, it is the equivalent of writing the following method:

def name=(new_name)
  @name = new_name
end

You would the refer to this elsewhere in your code as the following:

def some_method
  self.name = "Hossam"
end

This is necessary or, as Jessica Hori said, Ruby will attempt to access a local variable rather than a global one. Hope that helps!