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