Newbie question re. blocks & variable scope



  • 1. Ferret 0.1.0 (Port of Java Lucene) released
    Atm i'm using jruby to use lucene search, but this definitely sounds great!!! Do you have any plans to include snowball stemmers? As my documents are not english, i could use them ;)
  • 2. I was sold by Ruby
    Something to share with you (ladys and guys). My boss want me to compare data from two sources for oil busisness. As our routine, I write it in perl. But the output is wrong. So I think it must be wrong with logic or bug in perl. I convinced my boss to write the same program in Ruby(He really do not like to try new thing). The output is still wrong (same as perl output). So there is not perl bug, but my logic is wrong. Later, I found out what is wrong in my logic. And what I recognise my Ruby program is much shorter and beautier than my perl program. A further analysis, I see Ruby's beauty is its object oriented design. So I was sold to Ruby. Good Work ladys and guys!

Newbie question re. blocks & variable scope

Postby stevec890 » Tue, 20 Jan 2004 04:07:16 GMT


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?


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"
print "after:\n"
print "a=",a," b=",b,"\n"
idx=1: a=11
idx=2: a=nil b=12
test.rb:12: undefined local variable or method `a' for main:Object

Re: Newbie question re. blocks & variable scope

Postby Shashank Date » Tue, 20 Jan 2004 06:14:32 GMT

Correct (so far ;-) !

Ah ha ! You are using the term _iteration_ to mean a
"looping construct" (control structure) and then in the example
using "each" which is an "iterator" (method).

In Ruby, a looping construct is _not the same_ as an iterator.
An iterator may be implemented using "yield" and some form
of a looping construct. This is nicely explained in Pickaxe.

Which is because you are using each (iterator).

Read the later half of  Chapter 7 of PickAxe carefully, esp. the sub-topics
"Loops" onwards.

If you rewrite this using a _looping construct_ such as

for idx in data
  if (idx == 1)
    a = 11
    puts "idx=#{idx}: a=#{a}"
  elsif (idx == 2)
    b = 12
    p "idx=#{idx}: a=#{a} b=#{b}"

then you should get the desired behavior.

Does that make sense ?

-- shanko

Re: Newbie question re. blocks & variable scope

Postby Kenta MURATA » Tue, 20 Jan 2004 06:28:46 GMT

In message < XXXX@XXXXX.COM > at Mon, 19 Jan 2004 04:10:03 +0900,

Local variable is defined when it is parsed.  And block
internal scope is initialized each block call.  That is, in
the idx == 2 iteration, Ruby do:

(1) initialize block internal scope.
(2) parse ``a = 11'' line and define variable `a'.
(3) reference varaible `a', but it is not initialized (== nil).

1024D/2A3FDBE6 2001-08-26 Kenta MURATA (muraken) < XXXX@XXXXX.COM >
Key fingerprint = 622A 61D3 280F 4991 4833  5724 8E2D C5E1 2A3F DBE6

Similar Threads:

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


I am trying to understand the syntax error I receive in a code similar to

1 require 'logger'
3 log =  #some other logger settings are ignored.

4 def func
5   log.debug "a statement" # error is reported here when func is called
6  # some code
7 end
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?


2.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.

  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)


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

can be written as:

  p line

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

  print line + "\n"

can be:

  puts line

Hope this helps,




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

Hi, group!

This morning, a question came into my mind (I'm still a newbie).
What's the meaning of a top-level variable?

t = "top"
$g = "global"

puts t
puts $g

def f
  puts t #error
  puts $g


I know that a top-level variable cannot be used in a method.

My questions are:

1. Do you use top-level variables instead of global variables if you
don't need to use it in a method? Is it a good practice to use it like

2. What is a top-level variable? Is it an object variable or a local
variable or what?

3. What is the exact scope of a top-level variable?


4.newbie scope question


Thank you answers to my previous question(s) !

Why does this not work?

doc = File::open("my.txt")
    class Crap
              def junko
            @doc = doc
             @doc.each {|line| print line}

The segment below does work - I just don't quite understand why the Crap 
object can't 'see' the txt file in the above example...

doc = File::open("my.txt")
class Crap
  def junko(a)
  a.each {|line| print line}

Thanks in advance 

5.Question about variable scope

Does the following code behave as you'd expect?

  2.times{|n| i,j = n,i; puts "i=#{i}, j=#{j.inspect}"}

Can you explain why j is nil rather than 0, the second time round?


6. question modules and class variable scope

7. Newbie: Block Local Variable Inheritance

8. Newbie question: Small blocks

Return to ruby


Who is online

Users browsing this forum: No registered users and 22 guest