I have been taught to declare my instance variables with def initialize
. I have been under the impression that I could declare instance variables only within my initialize
methods.
Nevertheless, I declared an instance variable @foo
outside my initialize
method, and made it work as I intended:
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
Why am I able to declare an instance variable outside of initialize
method? Since I can declare instance variables in any method, is there a best practices rule I should follow, regarding where to declare instance variables (i.e., declare them within initialize
) or does it not matter?
I have been taught to declare my instance variables with def initialize
Since initialize
is the first instance method call in an object's life cycle, you typically declare your instance variables right there in order to ensure properly initialized variables. It's also the first place I'd expect instance variables to be defined when reading code.
I have been under the impression that I could declare instance variables only within my initialize methods.
There's no such restriction. You can declare instance variable anywhere within your instance.
A common use is memoization:
class FooBar
def foo
@foo ||= expensive_operation
end
end
On the first call, this would evaluate expensive_operation
and assign the result to @foo
. On subsequent calls, @foo
is returned.
Another popular example is Rails which uses instance variables to pass data from the controller to its 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
It depends on their purpose (see above examples). As a general rule, declare them in a way that avoids undefined variables (nil
errors) and structure your code so it is easy to read / follow.