patternrubyCritical
What is attr_accessor in Ruby?
Viewed 0 times
rubywhatattr_accessor
Problem
I am having a hard time understanding
Can someone explain this to me?
attr_accessor in Ruby.Can someone explain this to me?
Solution
Let's say you have a class
Obviously we never defined method
Aha, we can read the name, but that doesn't mean we can assign the name. Those are two different methods. The former is called reader and latter is called writer. We didn't create the writer yet so let's do that.
Awesome. Now we can write and read instance variable
Even this can get repetitive. When you want both reader and writer just use accessor!
Works the same way! And guess what: the instance variable
That's it. In order to understand how
Person.class Person
end
person = Person.new
person.name # => no method errorObviously we never defined method
name. Let's do that.class Person
def name
@name # simply returning an instance variable @name
end
end
person = Person.new
person.name # => nil
person.name = "Dennis" # => no method errorAha, we can read the name, but that doesn't mean we can assign the name. Those are two different methods. The former is called reader and latter is called writer. We didn't create the writer yet so let's do that.
class Person
def name
@name
end
def name=(str)
@name = str
end
end
person = Person.new
person.name = 'Dennis'
person.name # => "Dennis"Awesome. Now we can write and read instance variable
@name using reader and writer methods. Except, this is done so frequently, why waste time writing these methods every time? We can do it easier.class Person
attr_reader :name
attr_writer :name
endEven this can get repetitive. When you want both reader and writer just use accessor!
class Person
attr_accessor :name
end
person = Person.new
person.name = "Dennis"
person.name # => "Dennis"Works the same way! And guess what: the instance variable
@name in our person object will be set just like when we did it manually, so you can use it in other methods.class Person
attr_accessor :name
def greeting
"Hello #{@name}"
end
end
person = Person.new
person.name = "Dennis"
person.greeting # => "Hello Dennis"That's it. In order to understand how
attr_reader, attr_writer, and attr_accessor methods actually generate methods for you, read other answers, books, ruby docs.Code Snippets
class Person
end
person = Person.new
person.name # => no method errorclass Person
def name
@name # simply returning an instance variable @name
end
end
person = Person.new
person.name # => nil
person.name = "Dennis" # => no method errorclass Person
def name
@name
end
def name=(str)
@name = str
end
end
person = Person.new
person.name = 'Dennis'
person.name # => "Dennis"class Person
attr_reader :name
attr_writer :name
endclass Person
attr_accessor :name
end
person = Person.new
person.name = "Dennis"
person.name # => "Dennis"Context
Stack Overflow Q#4370960, score: 2589
Revisions (0)
No revisions yet.