我被教导用def initialize
来声明我的实例变量。我的印象是我只能在我的 initialize
方法中声明实例变量。
尽管如此,我在 initialize
方法之外声明了一个实例变量 @foo
,并使其按我的预期工作:
class FooBar
def initialize(bar)
@bar = bar
end
def foo_as_instance_var
@foo = @bar.split(' ')
@foo
end
end
x = "something wicked this way comes"
y = FooBar.new(x)
puts y.foo_as_instance_var
为什么我可以在 initialize
方法之外声明一个实例变量?由于我可以在任何方法中声明实例变量,关于在何处声明实例变量(即在 initialize
中声明它们)是否有我应该遵循的最佳实践规则,还是无关紧要?
最佳答案
I have been taught to declare my instance variables with def initialize
由于 initialize
是对象生命周期中的第一个实例方法调用,您通常会在那里声明实例变量,以确保正确初始化变量。这也是我希望在阅读代码时首先定义实例变量的地方。
I have been under the impression that I could declare instance variables only within my initialize methods.
没有这样的限制。您可以在实例中的任何位置声明实例变量。
一个常见的用法是 memoization :
class FooBar
def foo
@foo ||= expensive_operation
end
end
在第一次调用时,这将评估 expensive_operation
并将结果分配给 @foo
。在后续调用中,返回 @foo
。
另一个流行的例子是 Rails,它使用实例变量将数据从 Controller 传递到它的 View :
class FooController < ApplicationController
def index
@foos = Foo.all
end
end
is there a best practices rule I should follow, regarding where to declare instance variables
这取决于他们的目的(见上面的例子)。作为一般规则,以避免 undefined variable (nil
错误)的方式声明它们并构建您的代码以便于阅读/遵循。
关于ruby - 在 `initialize` 方法之外声明一个实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54192677/