Variable scopes with code blocks.

A

Aaron Gray

Hello!

Novice here. I'm reading Beginning Ruby and Beginning Rails by Apres and
building both applications they walk you through. Additionally, I'm
taking courses at lynda dot com and attempting to build a simple
application myself.

That said, I'm aware of the limits you have with local variable being
incapable of accessing variables defined inside of a code block, but is
there any exception to this rule?

Example:
_____________

1.times do
File.open("text.txt").each {|a| puts a}
end

puts a
# This where I get my error.
_____________

Is there anything I can do to 'puts a' that will allow it to return the
content it was passed inside of the code block?

Ultimately, I'd like to store the 'text.txt' as an array so I can call
uniq! on it... But we don't need to get into that in this thread.

I hope my question makes sense.

Thank you in advanced,
Aaron
 
7

7stud --

Aaron Gray wrote in post #1001620:
Hello!

Novice here. I'm reading Beginning Ruby and Beginning Rails by Apres and
building both applications they walk you through. Additionally, I'm
taking courses at lynda dot com and attempting to build a simple
application myself.

That said, I'm aware of the limits you have with local variable being
incapable of accessing variables defined inside of a code block, but is
there any exception to this rule?

Example:
_____________

1.times do
File.open("text.txt").each {|a| puts a}
end

puts a
# This where I get my error.
_____________

Is there anything I can do to 'puts a' that will allow it to return the
content it was passed inside of the code block?


arr = []

Io_Open('text.txt') do |line|
arr << line
end

p arr

Ultimately, I'd like to store the 'text.txt' as an array so I can call
.uniq! on it... But we don't need to get into that in this thread.

arr = File('text.txt').readlines
 

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

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top