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

后端 未结 4 2023
粉色の甜心
粉色の甜心 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
    
    0 讨论(0)
  • 2021-01-13 16:55

    There's self, like:

    def account_id
      self.account.id
    end
    
    0 讨论(0)
  • 2021-01-13 17:00

    You can call self.whatever on the class you are in, is that what you are looking for?

    0 讨论(0)
  • 2021-01-13 17:04

    How about

    self

    An example:

    self.name

    0 讨论(0)
提交回复
热议问题