Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby equivalent to PHP's $this

Tags:

oop

php

ruby

this

What is the equivalent of PHP's $this-> in Ruby?

like image 268
user1432856 Avatar asked Jun 03 '12 16:06

user1432856


2 Answers

The ruby equivalent of this is self - they both refer to the current instance.

The tricky part is that in Ruby class scope, self refers to the current instance of the class Class that defines the class you are building. Inside a method, self refers to the instance of the class.

eg:

class Example
  puts self  # => "Example" - the stringified class object

  def foo
    puts self  # #<Example:0xdeadbeef> - the stringified instance
  end
end
like image 173
Daniel Pittman Avatar answered Sep 29 '22 04:09

Daniel Pittman


The analog of $this is self, as has been mentioned. However, you asked about $this->, which means you want to use it to access an instance variable ($this->somevar) or instance method (this->somemethod()). For an instance variable, the equivalent in Ruby would be @ (as in @somevar). For instance methods, the equivalent would be to just write the method name (somemethod), or, if you like to be verbose (self.somemethod).

like image 43
newacct Avatar answered Sep 29 '22 03:09

newacct