Hello,
I am trying to understand the syntax error I receive in a code similar
to
this.
1 require ‘logger’
2
3 log = logger.new #some other logger settings are ignored.
4 def func
5 log.debug “a statement” # error is reported here when func is called
below
6 # some code
7 end
8
9 #some code continues
10 func
When func is called, an error is reported on line-5 saying that undefine
local variable log etc. I understand that functions create scopes and
log is
seen as local variable which is not defined in that scope. As it is
qualified with no scope operator, interpreter thinks that it is local
but
can not find definition of the log before it’s usage but also in the
parameter list and I understand that. On the other hand, I can use log
without qualifying it with a scope symbol anywhere in the same file if
it is
not in a function. I know that loops, if statements etc are built into
the
language and do not create scope. Code blocks inherit the locals. So it
is
meaningful that I can use it anywhere else. When I qualify log with $ as
$log, it becomes global and I no longer receive error. I have tried it
qualifying with @ etc. but the received the same error. What I am asking
is,
what is scope of log?. What kind of variable is it? It is the local or
instance variable of what, Object? I know that func is private to the
Object. But what about log? How can I access it in a function
without
making it global?
Is there a way to make variables local to a file as perl does with “my”.
Is there a strict option that prevents unintended variable creation
because
of typos. Is there a way force predeclaration of variables?
Thanks.