Kevin
Kevin

Reputation: 1120

Advantages of self.attribute vs. @attribute?

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

Upvotes: 6

Views: 1235

Answers (3)

Colin Curtin
Colin Curtin

Reputation: 2353

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.

Upvotes: 4

horseyguy
horseyguy

Reputation: 29895

Further to Peter's answer:

Another interesting point is that self.salt= can be invoked even if the salt= method is private. This is an exception to the normal Ruby rule that a private method can not be invoked with an explicit receiver.

Upvotes: 2

Peter
Peter

Reputation: 132227

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.

Upvotes: 13

Related Questions