I am new to Ruby language. I understand that
@@count: Class variables
@name: Instance variables
my_string: Local variables
I keep the above in mind. However, I found one Ruby code like this:
class HBaseController < ApplicationController
...
def result
conn = OkHbase::Connection.new(host: 'localhost', port: 9090, auto_connect: true)
...
end
end
'conn' confuses me a lot.
Is 'conn' a instance variable, or local variable? And what is the scope of 'conn'?
In this case,
conn
is local variable.EDIT:
conn would be a instance variable if you had it written like
@conn = OkHbase::Connection.new(host: 'localhost', port: 9090, auto_connect: true)
conn
is local to the methodresult
Blocks create a new scope, as do methods and class declarations. Interestingly,
if
statements do not create a new local scope, so variables you declare inside of anif
statement is available outside.I try to explain it with a little example:
conn
is unknown. Let's try to callmeth
before:Same result. So
conn
is no instance variable. You define a local variable inmeth
but it is unknown outside.Let's try the same with instance variables:
With the usage of accessor-methods you define implicit an instance variable:
In method
result
theconn
is the reader methodconn
. In the methodmeth
it is a locale variable (this can be confusing, because now you have a variable with the same name as a variable.If you want to change the
conn
-value in themeth
-method you must define a setter and useself.conn
:You can replace
attr_reader
andattr_writer
withattr_accessor
.(*) Remark: I wrote no value assigned - this is not really correct,
nil
is also a value.conn
is a local variable (local variables start with a lower case letter or an underscore)It contains an instance of OkHbase::Connection
Presumably the code that was omitted
...
uses that object. Because it's a local variable, once theresult
method is ended, the local variable will no longer be accessible and the object will be cleared from memory.(Of course, it's possible the omitted code assigned the object in
conn
to an instance variable or passed it into some other method that has stored it elsewhere)