Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of self.attribute vs. @attribute?

Tags:

ruby

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

like image 759
Kevin Avatar asked Dec 09 '09 23:12

Kevin


2 Answers

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.

like image 130
Peter Avatar answered Sep 20 '22 08:09

Peter


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.

like image 27
Colin Curtin Avatar answered Sep 19 '22 08:09

Colin Curtin