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