Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Ruby equivalent of the "this" function in Java?

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
like image 223
Lino Avatar asked Feb 15 '23 21:02

Lino


2 Answers

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
like image 185
Mohamad Avatar answered Feb 24 '23 07:02

Mohamad


There's self, like:

def account_id
  self.account.id
end
like image 31
James Chevalier Avatar answered Feb 24 '23 05:02

James Chevalier