-3

What does ruby self represent? what is it? what does it mean? Could some please explain it to me? in simple terms please And what is its function in a class?

class MyClass
   def method.self
   end
end
Radosław Miernik
  • 4,004
  • 8
  • 33
  • 36
  • 3
    Where you saw this piece of code? I think, `self` is misplaced.. :) Please read through this [blog](http://www.jimmycuadra.com/posts/self-in-ruby/) to understand what is `self` .. – Arup Rakshit Jan 31 '16 at 17:55
  • 1
    It is explained in Ruby Documentation- http://ruby-doc.org/docs/keywords/1.9/Object.html#method-i-self. Have a look at [How to ask a question](http://stackoverflow.com/help/how-to-ask) and make sure that you have done sufficient research and post specific question. – Wand Maker Jan 31 '16 at 17:56
  • @WandMaker Help us to close this question.. :) – Arup Rakshit Jan 31 '16 at 17:57
  • The book _The Well-Grounded Rubyist_ covers _self_ quite well I think. – Sagar Pandya Jan 31 '16 at 20:40
  • You need to do more research before asking: http://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users, and http://catb.org/esr/faqs/smart-questions.html. – the Tin Man Feb 01 '16 at 03:17

1 Answers1

8

self refers to the object that is currently in context.

In your example, self is the class itself and def self.method is defining a class method. For example:

class MyClass
  def self.method
    puts "Hello!"
  end
end

> MyClass.method
#=> "Hello"

You can also use self on instances of a class.

class MyClass
  def method_a
    puts "Hello!"
  end

  def method_b
    self.method_a
  end
end 

> m = MyClass.new
> m.method_b
#=> "Hello!"

In this case, self refers to the instance of MyClass.

There is a good blog post on self in Ruby here, or, as it was pointed out in the comments, there is some more on this in the Ruby documentation.

philnash
  • 70,667
  • 10
  • 60
  • 88