Question about variable scope

R

robin

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?

Thanks,
Robin
 
T

Thomas Hafner

robin said:
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?

I'll try. Everytime the block is executed, new variables n, i and j
are created, because they don't already exist outside the block. If
you want i to be shared, it should already exist before, e.g.:

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

Regards
Thomas
 
R

robin

I'll try. Everytime the block is executed, new variables n, i and j
are created, because they don't already exist outside the block. If
you want i to be shared, it should already exist before, e.g.:

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

Thanks for the reply. I think I've succeeded in adjusting my mental
model enough that this now makes sense. :)

Robin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

First time question 1
variable scope 2
Question about my projects 3
Lexical vs Dynamic Scope 3
Need help in debugging tic tac toe (Beginner) 0
TF-IDF 1
scope puzzle 2
Problems w/ Tk::Tile::Label.new scope? 1

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,169
Latest member
ArturoOlne
Top