newbie question about scope, variables, declarations of variables and option strict (as in perl)

ruby

    Next

  • 1. rdoc help needed
    Hello, I'm preparing a class on ruby, and I decided to write the exercices as ruby files with function stubs and rdoc comments. Additionally I'm defining unit tests, such that the student can test his program to complie with the unit tests. What I would like to have would be a simpler rdoc output. Mainly parsing the file from top to bottom, and outputting marked up comments and ruby source as it is encountered in the file. Is this already possible, or do I have to write something myself. Alternatively, if someone knows a better approach I'm also open to it. Regards, Brian

newbie question about scope, variables, declarations of variables and option strict (as in perl)

Postby Talha Oktay » Thu, 09 Mar 2006 18:01:37 GMT


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.


Re: newbie question about scope, variables, declarations of variables and option strict (as in perl)

Postby James Edward Gray II » Thu, 09 Mar 2006 22:50:36 GMT




No, this works too (after you fix your Logger constructor call):

require 'logger'

@log = Logger.new("test.log")  #some other logger settings are ignored.

def func
   @log.debug "a statement" # error is reported here when func is  
called below
   # some code
end

#some code continues
func



It's a local variable, scoped to the file it is defined in.  It would  
not be available inside class, module, or method definitions though,  
because they are not closures.


Local.


To the file.


You could pass it as a parameter, or make it an instance variable, as  
shown above.


This is how it functions.


You must assign to a local before you can use it in Ruby.  That's why  
you got the error.  ;)

James Edward Gray II




Re: newbie question about scope, variables, declarations of variables and option strict (as in perl)

Postby dblack » Thu, 09 Mar 2006 23:39:10 GMT

Hi --







That's a different @log from the one you assigned to, though.


David

-- 
David A. Black ( XXXX@XXXXX.COM )
Ruby Power and Light, LLC ( http://www.**--****.com/ )

"Ruby for Rails" chapters now available
from Manning Early Access Program!  http://www.**--****.com/ 



Re: newbie question about scope, variables, declarations of variables and option strict (as in perl)

Postby James Edward Gray II » Fri, 10 Mar 2006 00:07:01 GMT






I'm not sure why you say this, but you're wrong.  ;)  Here's the proof:

Neo:~/Desktop$ ls
log.rb
Neo:~/Desktop$ cat log.rb
require 'logger'

@log = Logger.new("test.log")  #some other logger settings are ignored.
p @log.object_id

def func
   @log.debug "a statement" # error is reported here when func is  
called below
   p @log.object_id
   # some code
end

#some code continues
func
Neo:~/Desktop$ ruby log.rb
923180
923180
Neo:~/Desktop$ cat test.log
# Logfile created on Wed Mar 08 09:04:50 CST 2006 by logger.rb/1.5.2.7
D, [2006-03-08T09:04:50.196373 #5517] DEBUG -- : a statement

James Edward Gray II




Re: newbie question about scope, variables, declarations of variables and option strict (as in perl)

Postby dblack » Fri, 10 Mar 2006 00:38:21 GMT

Hi --









Weird.  I guess Logger does something bizarre in its constructor.


David

-- 
David A. Black ( XXXX@XXXXX.COM )
Ruby Power and Light, LLC ( http://www.**--****.com/ )

"Ruby for Rails" chapters now available
from Manning Early Access Program!  http://www.**--****.com/ 



Re: newbie question about scope, variables, declarations of variables and option strict (as in perl)

Postby James Edward Gray II » Fri, 10 Mar 2006 00:47:04 GMT




I guess I don't understand what you are getting at.  This is the  
normal behavior for any object:

Neo:~/Desktop$ ls
test.rb
Neo:~/Desktop$ cat test.rb
@obj = Object.new
p @obj.object_id

def func
   p @obj.object_id
end

func
Neo:~/Desktop$ ruby test.rb
957270
957270

James Edward Gray II




Re: newbie question about scope, variables, declarations of variables and option strict (as in perl)

Postby gwtmp01 » Fri, 10 Mar 2006 00:56:54 GMT




At the top level 'self' references the same object in the file scope
and in the method scope (really private instance methods of the top- 
level
object).  Why then is it puzzling that the instance variables are
accessible from either place?


   @a = 'this is @a'
   puts "top: self: #{self.object_id}"
   puts "top: @a: #{@a}"

   def foo
     puts "foo: self: #{self.object_id}"
     puts "foo: @a: #{@a}"
   end
   foo

put that code in a file and run it:

top: self: 1019060
top: @a: this is @a
foo: self: 1019060
foo: @a: this is @a



Gary Wright






Re: newbie question about scope, variables, declarations of variables and option strict (as in perl)

Postby dblack » Fri, 10 Mar 2006 00:58:01 GMT

Hi --







For some reason I had hallucinated that the original example was
inside a class definition body, rather than at the top level.  Ignore
me....


David

-- 
David A. Black ( XXXX@XXXXX.COM )
Ruby Power and Light, LLC ( http://www.**--****.com/ )

"Ruby for Rails" chapters now available
from Manning Early Access Program!  http://www.**--****.com/ 



Re: newbie question about scope, variables, declarations of variables and option strict (as in perl)

Postby dblack » Fri, 10 Mar 2006 01:11:24 GMT

Hi --






See my last message -- for some reason I projected a class definition
body onto the example when I read it.


David

-- 
David A. Black ( XXXX@XXXXX.COM )
Ruby Power and Light, LLC ( http://www.**--****.com/ )

"Ruby for Rails" chapters now available
from Manning Early Access Program!  http://www.**--****.com/ 



Similar Threads:

1.variable scope and use strict

I am trying to use strict all the time now.  I have a problem with the
following code.  When I use strict the value of $highest won't leave the
foreach construct.  I know this is by design but I cannot figure out how
make that variable available outside the loop.  Any advice?

Also if someone could tell me where to find perldoc regarding "use
strict;" or scoping in general I would appreciate it.


#!/usr/bin/perl
my $number = 1;
my $dir = "/etc/backup";
opendir DIR1, $dir;
my @files = readdir(DIR1);
closedir DIR1;
foreach my $filename (@files)
    {
        push(@filenum, $1)  if ($filename =~ /^CUX(\d+)\.txt$/);
        #my $highest = (sort { $a <=> $b } @filenum)[-1];
     }
        $highest = (sort { $a <=> $b } @filenum)[-1];
        $final = $highest + $number;
print "CUX00" . "$final" . ".txt\n";


2.[newbie] scope of the variables

Hi all,


I am trying to create a module. and I have a question about the scope
of the variables.



lets say,

use strict;


sub one {

    my ($rvalue) = @_;   # here I define a variable

    for my $i (0..$#$rvalue){   # here I define a local 
                                # variable $i and I use it

        # do something
    }

}


sub second {

    my ($rvalue) = @_;   # on this second sub $rvalue 
                         # is a new one or I carry it
                         # as the first one

    
    for my $i (0..$#$rvalue){ # now the same case, $i was
                              # already defined and if the
                              # scope is just its
                              # own subsroutine, now this
                              # $i is something copletely
                              # new. Am I right?

      # do something else
   }
}


 # Thanks for your help
 # John

3.Newbie Question. eval.rb variable scope issue

From: "Rishel,Wes" < XXXX@XXXXX.COM >
> 
> I am a Python duffer who got interested in Rails an decided to check out
> Ruby.
> 
> This dandy little Ruby script illustrates the issue
> 
> a = ['word = 2', 'word']
> 
> a.each do | line |
>        begin
>               print eval(line).inspect, "\n"
>        rescue ScriptError, StandardError
>               print line + "\n"   # WJR change
>               printf "ERR: %s\n", $! || 'exception raised'
>        end
> end
> 
> After some perusing the available on-line manuals I have not been able
> to find a way to fix eval.rb to remember the scope of variables created
> in the input to it. Perhaps I am missing something obvious?

Welcome !

I don't know the exact reason, but it seems you'll need to
obtain a binding context from outside the iterator block.
E.g.

  a = ['word = 2', 'word']
  b = binding
  a.each {|line| p( eval(line, b) ) }


Incidentally, have you found `irb` yet?  There should be an irb.bat
in the bin directory next to your ruby.exe.  IRB is "interactive
ruby", similar to invoking python with no arguments.

A couple tips:

  p(expr) is a shortcut for puts(expr.inspect)

So,

  print eval(line).inspect, "\n"

can be written as:

  p line

Also, puts is like print, but adds the "\n" for you.
So,

  print line + "\n"

can be:

  puts line



Hope this helps,

Regards,

Bill

  

4.Newbie question re. blocks & variable scope

Hi,

I'd like to ask for some help with local variable scope.  I understand
that the scope of a local variable is the "do...end" block in which it
is created.  However, the code below shows that the value assigned to
the variable within a block does not persist after the single
iteration in which the variable is given that value, although the
variable is still defined in a later iteration. That is, in the idx=2
iteration, Ruby does not remember that a=11 in the previous iteration,
but it also does not complain about an undefined local variable "a"
(which it of course does outside the block). I haven't been able to
find this behavior mentioned in the documentation or in this
group--can you point me to something that will clarify for me what is
going on?

Thanks,
Steve

data=[1,2]
data.each do | idx|
	if idx == 1
		a = 11
		print "idx=1: a=",a,"\n"
	elsif idx == 2
		b = 12
		print "idx=2: a=",a," b=",b,"\n"
	end
end
print "after:\n"
print "a=",a," b=",b,"\n"
	
>c:\ruby\bin\ruby test.rb
idx=1: a=11
idx=2: a=nil b=12
after:
test.rb:12: undefined local variable or method `a' for main:Object
(NameError)
>Exit code: 1

5.Question about Modules and Variable Scope

6. Question about variable scope

7. question about "package" and variable scope...

8. Newbie Question: Global variable vs. Top-level variable



Return to ruby

 

Who is online

Users browsing this forum: No registered users and 21 guest