why i can't get the value out of each block?

P

Pen Ttt

a=[1,2,0,10]
a.each.with_index{|item,idx|
begin
puts 10/item
rescue
print "it is my wrong ",item,idx,"\n"
x=item
end}
puts "x=",x


the output is :NameError: undefined local variable or method `x' for
main:Object
why i can't get the value out of each block?
 
A

Ayumu Aizawa

Hi

In that case, x has scope of inside block.
if you want to reffer x out of blok, sould initialize before block.
like berow.

a=3D[1,2,0,10]
x=3Dnil
a.each_with_index {|item, idx|
begin
puts 10 / item
rescue
print "it is my wrong ",item,idx,"\n"
x=3Ditem
end}
puts "x=3D",x
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,062
Latest member
OrderKetozenseACV

Latest Threads

Top