What does self mean?

Technology CommunityCategory: RubyWhat does self mean?
VietMX Staff asked 3 years ago

self always refers to the current object. But this question is more difficult than it seems because Classes are also objects in ruby.

class WhatIsSelf
  def test
    puts "At the instance level, self is #{self}"
  end

  def self.test
    puts "At the class level, self is #{self}"
  end
end

WhatIsSelf.test 
 #=> At the class level, self is WhatIsSelf

WhatIsSelf.new.test 
 #=> At the instance level, self is #<WhatIsSelf:0x28190>

This short snippet indicates two things:

  • at the class level, self is the class, in this case WhatIsSelf.
  • at the instance level, self is the instance in context, in this case the instance of WhatIsSelf at memory location 0x28190.