What does self mean?

Technology CommunityCategory: RubyWhat does self mean?
VietMX Staff asked 2 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}"

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

 #=> At the class level, self is WhatIsSelf

 #=> 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.