Ruby equivalent to PHP's $this

送分小仙女□ 提交于 2019-11-29 14:26:40

问题


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


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/10871940/ruby-equivalent-to-phps-this

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!