InQusitive InQusitive - 26 days ago 13
Ruby Question

What is a self reference in ruby?

Currently I am reading

The Ruby Programming Language
and it has mentioning of
self
in many places and I am not able to understand it's exact use. Is its behaviour similar to
this
pointer in C++.What all difference those two have?(I am not asking about the pointer dereferencing or any C++ specific things, in general) And when do we use
self.something
in our ruby code?

Answer

self is a variable that points to the object whose scope the current code is in. You would use self.something when calling a class method on that object.
For instance, if you had the following method:

class Foo
    def self.bar 
       puts "Class method!"
    end 
end   

You would call the bar method by calling Foo.bar.

Comments