Explicitly specify default method target in Ruby?
Is there开发者_开发技巧 a best practice in Ruby when it comes to explicitly specifying method targets even when unnecessary?
class Foo
def meth1
puts "bar"
end
def meth2
# is this better?
self.meth1
# or this?
meth1
end
end
No, it's just a question of style.
The only thing to keep in mind is that you always have to specify a target for setter methods.
foo_count = 4 #creates a local variable named foo_count and sets it to 4
self.foo_count = 4 #sends foo_count=(4) to self
The same rule applies if you happen to have a local variable with the same name as a method of your class, though I would say that is a bad practice in itself.
As Chuck said earlier, it is mostly a matter of style with the exception he pointed out, and when using private methods. Any time you use a private method from within an object, you must leave off the self.
business.
Eg:
class Tze
def meth2
meth1
end
def meth3
self.meth1
end
private
def meth1
puts "method 1 invoked"
end
end
Calling Tze.new.meth2
produces the expected output; however, calling Tze.new.meth3
raises an error because of meth1
is being invoked as self.meth1
.
精彩评论