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
There's self
, like:
def account_id
self.account.id
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With