有几个重要的用途,其中大部分基本上是为了消除实例方法、类方法和变量之间的歧义。
首先,这是定义类方法的最佳方式:
class Foo
def self.bar
"class method bar"
end
def bar
"instance method bar"
end
end
Foo.bar #returns "class method bar"
foo = Foo.new
foo.bar #returns "instance method bar"
另外,在实例方法中self
指的是实例,在类方法中它指的是类,并且它总是可以用来与局部变量区分开。
class Bar
def self.foo
"foo!"
end
def baz
"baz!"
end
def self.success
foo #looks for variable foo, doesn't find one, looks for class method foo, finds it, returns "foo!"
end
def self.fail
baz #looks for variable baz, doesn't find one, looks for class method baz, doesn't find one, raises exception
end
def instance_success
baz #looks for variable baz, doesn't find one, looks for instance method baz, finds it, returns "baz!"
end
def instance_fail
foo #looks for variable foo, doesn't find one, looks for instance method foo, doesn't find one, raises exception
end
def local_variable
baz = "is my favorite method"
baz #looks for variable baz, finds it, returns "is my favorite method"
end
def disambiguate
baz = " is my favorite method"
self.baz + baz #looks for instance method baz, finds it, looks for local variable baz, finds it, returns "baz! is my favorite method"
end
end
所以,最后,你可以避免使用self
在许多情况下,但使用它通常会很有帮助,以确保您以后不会无意中造成命名冲突。有时,这些可能会产生很难发现的错误。最终,这通常是个人风格的问题。
正如评论中指出的,还有一件非常重要的事情:
在一个类中,如果你有这样的方法:
def bar=(string)
...
end
在另一种方法中,您调用:
def other_method
bar = "abcd"
end
它不会打电话给你bar=
方法,它将创建一个局部变量bar
。所以,在这种情况下你使用self
告诉 Ruby 不要创建局部变量:
def other_method
self.bar = "abcd"
end
如果您想使用方法名称作为参数,同样的情况也适用:
def example
...
end
def other_thing(example)
self.example(example)
end
如果你离开了self
Ruby 会假设您指的是同名的局部变量。
所以,一般来说,self
方法名称中用于区分类变量和实例变量,当 Ruby 需要帮助区分方法调用和局部变量或局部变量赋值时,在其他任何地方都可以使用它。
我希望这是有道理的。