Assuming the following:
def create_new_salt
self.salt = self.object_id.to_s + rand.to_s
end
Why is it better to use the 'self.' rather than an instance variable '@salt'?
Using self.salt =
will cause the salt=
method to be used, if defined. This is useful for ensuring any error checking / transformations inside the salt=
method are used. However, it means there must be an explicit salt=
method (possibly created by attr_accessor
, for example), and this isn't necessarily a good idea.
Summary: use self.salt =
if you have a custom salt=
method; use @salt =
if you know exactly what you want @salt
to be, or if you don't have a custom salt=
method.
Final note: I'd probably write it like this (in my opinion it's a little clearer)
def create_new_salt
@salt = "#{object_id}#{rand}"
end
EDIT: thanks to @Chuck's comments on another answer, I've modified this to remove the self.
-free code - it was wrong.
Besides Peter's great answer, I usually signal in Ruby that I'm using attr_accessor
by using self.attr= and self.attr instead of @attr.
Edit: Without "self.", you're creating a local variable. Yikes.
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