I am trying to get a good Ruby coding style. To avoid accidentally calling a local variable with the same name, I always use self.it where necessary. But now I came across this:
self.
class MyClass < ActiveRecord::Base before_validation :sanitize_user_data private def sanitize_user_data self.sanitize_name # with ".self" it a problem, without it not! end def sanitize_name unless self.name.nil? self.name.gsub!(/\s+/, ' ') self.name.strip! end end end
The above code results in an error
private method sanitize_namecalled
sanitize_name
but when removed self.and just using sanitize_name, it works. Why?
, , self.sanitize_name (self), sanitize_name, ( self).
self.sanitize_name
self
, sanitize_name , self.send(:sanitize_name). , self " ", . , , :
self.send(:sanitize_name)
def a; "method"; end a = "variable" a() #=> "method" a #=> "variable"
?
. , , private.
private