Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby method like `self` that refers to instance

Tags:

oop

ruby

Is there a method in Ruby that refers to the current instance of a class, in the way that self refers to the class itself?

like image 764
amindfv Avatar asked Aug 22 '12 17:08

amindfv


People also ask

What does self refer to in an instance method body Ruby?

Ruby has an answer: the self keyword. Within instance methods, self always refers to the current object.

What is self in a class method Ruby?

self is a reserved keyword in Ruby that always refers to the current object and classes are also objects, but the object self refers to frequently changes based on the situation or context. So if you're in an instance, self refers to the instance. If you're in a class, self refers to that class.

How do you call a self method in Ruby?

One practical use for self is to be able to tell the difference between a method & a local variable. It's not a great idea to name a variable & a method the same. But if you have to work with that situation, then you'll be able to call the method with self. method_name .

What is an instance Ruby?

In the Ruby programming language, an instance variable is a type of variable which starts with an @ symbol. Example: @fruit. An instance variable is used as part of Object-Oriented Programming (OOP) to give objects their own private space to store data.

What is instance of a class in Ruby?

Class Instances and Instance Methods In Ruby, a class is an object that defines a blueprint to create other objects. Classes define which methods are available on any instance of that class. Defining a method inside a class creates an instance method on that class.

What is the difference between class method and instance method?

Instance methods need a class instance and can access the instance through self . Class methods don't need a class instance. They can't access the instance ( self ) but they have access to the class itself via cls .


1 Answers

self always refers to an instance, but a class is itself an instance of Class. In certain contexts self will refer to such an instance.

class Hello
  # We are inside the body of the class, so `self`
  # refers to the current instance of `Class`
  p self

  def foo
    # We are inside an instance method, so `self`
    # refers to the current instance of `Hello`
    return self
  end

  # This defines a class method, since `self` refers to `Hello`
  def self.bar
    return self
  end
end

h = Hello.new
p h.foo
p Hello.bar

Output:

Hello
#<Hello:0x7ffa68338190>
Hello
like image 96
Josh Lee Avatar answered Sep 21 '22 13:09

Josh Lee