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 trialRonald Jackson
9,229 PointsDifference between a class variable and attr_accessor in Ruby?
I'm progressing along the Ruby/Rails Track. What is the difference, if any, between a "class variable" and an "attr_accessor" in Ruby?
When defining and working with classes & objects in Ruby, can class variables, which are denoted by @@, serve the same purposes as attr_accessors? If so, why use one over the other?
Thanks for any insights!
1 Answer
Kang-Kyu Lee
52,045 PointsHi Ronald. I heard attr_accessor
would be equivalent with getter-setter "instance" methods.
class Student
# getter method
def name
@name
end
# setter method
def name=(str)
@name = str
end
end
equivalent with
class Student
attr_accessor :name
end
which allows us to do something like this:
a_student = Student.new
a_student.name = "Somebody"
a_student.name # returns "Somebody"
Basically attr_accessor
turn instance variable into instance method ( like @ no longer required ) in the class definition. When an object (instance) calls a method it should look at the class of this instance and find instance method defined in.
But class method or class variables are quite different in a sense.
class Student
@@total_number_of_students
def self.count_them
end
end
and then it allows you call the variable and method directly from the class.
Student.total_number_of_student
Student.count_them
Thanks. I learn a lot trying to answer and discuss on forum
Ronald Jackson
9,229 PointsRonald Jackson
9,229 PointsHi Kang Kyu,
Thank you for the clarification. I'm new to Ruby and programming. You mentioned getter & setter methods. I wasn't familiar with those so I did more research. I found a good explanation on rubymonk.com:
http://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/45-more-classes/lessons/110-instance-variables
Thanks again for helping me to expand my understanding of Ruby.
Best regards,
Ronald