To be honest, I still confused about the instance variable and local variable, not sure which should be used.
only one condition I know about local variable that can't be used is:
class MyClass
def initialize
local_var = 1
@instance_var = 1
end
def show_local_var
local_var
end
def show_instance_var
@instance_var
end
end
apparently, MyClass.new.show_instance_var
works while MyClass.new_show_local_var
not
the other thing about the two kind of variables is that the block seems share the same local scope, so the local variable can be referenced:
local_var = 1
3.times do
puts local_var
end
There are all I know about the distinctions, is there any other available? please let me know
if there is any articles about this, that would be so helpful for me,
Local scope is limited to the location in which the variable is declared, i.e. a function, or a for loop, but cannot be accessed from outside that location. However, if you nest other constructs within the function, for loop, etc. then the inner constructs can access the local variable. Instance variables are scoped to the instance of the class.
Article on ruby variable scope
Article on scope in general
The second example you describe is called a Closure. Paul puts it quite nicely there:
For a nice, quick introduction about the available scopes in Ruby you may refer to the Ruby Programming wikibook.
There is
The "Default Scope", as it is sometimes referred to when executing code with no scope modifiers surrounding it, as in
is the scope of the 'main' object.
A local variable is used "right here right now" and can't be accessed from anywhere else.
Once you're out of scope (
foo
'send
is passed)local_var
is no more and can't be referred to.The instance variable is available to the whole class at all times.
So when you call
m = MyClass.new
and later onm.some_operation
, it's working with the same@instance_var
.And while we're at it, there are also Class variables (defined
@@class_var
) that are accessible from any instance of the class.I don't have an article in particular to provide you, but some googling about
ruby variable scope
and about each type of variable independently should provide you with all the information you need!