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.

Tomasz Jaśkiewicz
5,399 PointsWhat is the difference between self.foo and self.class.foo?
There is a method like this:
def self.create_for(first_name, last_name)
@accounts ||= []
@accounts << BankAccount.new(first_name, last_name)
end
and also:
def display
self.class.format_attributes.each do |attribute|
puts "[#{attribute.to_s.upcase}] #{send(attribute)}"
end
end
What is the difference between self.foo and self.class.foo?
2 Answers

Brandon Barrette
20,485 PointsSo self.foo acts on an instance. So if self is Status class, then self.foo acts on an instance of Status (usually a method you call to modify that specific status, add information, look up information, etc.)
self.class is going to give you the Status class, and from there you can call arguments on the class. But here, you aren't working with a specific instance. In other words, self.class.foo here is the same as Status.foo, assuming self.class is Status.

Christine Merey
3,309 PointsI found it helpful to add the lines puts self
and puts self.class
and see that it depends on the calling class; that you needed to specify self.class
to get the class name.
def display
puts self # => #<Resume:0x000000026bb7f8>; #<CV:0x000000026bb730>
puts self.class # => Resume; CV
self.class.format_attributes.each do |attribute|
puts "[#{attribute.to_s.upcase}] #{send(attribute)}"
end
end
So, what is self
here? l added puts self.inspect
, which output the instances of class Resume and class CV:
def display
puts self.inspect # => #<Resume:0x000000026bb7f8 @name="Kermit the Frog", @email="kermit@themuppetshow.org", @phone_number="1 800 555-1234", @experience="Hosting">
# => #<CV:0x000000026bb730 @name="Kermit the Frog", @experience="Hosting The Muppet Show">