What is the Ruby equivalent of the “this” function in Java?

后端 未结 4 2022
粉色の甜心
粉色の甜心 2021-01-13 16:36

In Java there is a \"this\" function that points to its method. Is there an equivalent in Ruby? For instance, is there:

def method
  this.method
end
<         


        
4条回答
  •  隐瞒了意图╮
    2021-01-13 16:45

    The equivalent is self. It is also implict. So self.first_name is the same as first_name within the class unless you are making an assignment.

    class Book
      attr_reader :first_name, :last_name
    
      def full_name
         # this is the same as self.first_name + ", " + self.last_name
        first_name + ", " + last_name
      end
    end
    

    When making an assignment you need to use self explicitly since Ruby has no way of knowing if you are assigning a local variable called first_name or assigning to instance.first_name.

    class Book    
      def foo
        self.first_name = "Bar"
      end
    end
    

提交回复
热议问题