scope - Ruby set local variable inside a block -
i have variable set default value on, , perform procedure on. thing is, don't have access variable inside block block has it's own variable scope , no access outside. here snippet:
value = "" cmd_errors = array.new # call command line status = popen4.popen4(cmd) |stdout, stderr| output = stdout.read error = stderr.read if (!output.empty?) value = json.parse(output) #this creates block scoped variable called 'value' , local variable still empty else cmd_errors << error end end
is possible allow block write local variable? perhaps using references?
in program, external value
variable is being modified block. usual assign nil
such external variables, have work fine.
try modifying value else inside block, this, , see variable being changed. guess output.empty?
coming true.
value = nil cmd_errors = array.new status = popen4.popen4(cmd) |stdout, stderr| output = stdout.read error = stderr.read value = 'within block' if (!output.empty?) value = json.parse(output) else cmd_errors << error end end p value
Comments
Post a Comment