开发者

Advantages of self.attribute vs. @attribute?

Assuming the following:

def create_new_salt
  self.salt =开发者_Go百科 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜