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.

Christine Merey
Christine Merey
3,309 Points

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