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 Foundations Modules Extend and Include: Part 2

Tomasz Jaśkiewicz
Tomasz Jaśkiewicz
5,399 Points

What 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
Brandon Barrette
20,485 Points

So 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.

I 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">