3

I have a variable which I set a default value on, and then I perform a procedure on. The thing is, I don't have access to the variable inside the block as the block has it's own variable scope and no access to the outside. Here is a snippet:

value = ""
cmd_errors = Array.new

# Call the command line
status = POpen4.popen4(cmd) do |stdout, stderr|
  output = stdout.read
  error  = stderr.read
  if (!output.empty?)
    value = JSON.parse(output)      #This just creates a block scoped variable called 'value' and my local variable is still empty
  else
    cmd_errors << error
  end
end

Is it possible to allow the block to write to that local variable? Perhaps using references?

2
  • could you use p output,error within the loop. Seems the if condition never becomes true. Commented Jul 17, 2013 at 21:09
  • @tolgap: p x is equivalent to puts x.inspect, so you shouldn't write p value.inspect as it is the same as puts x.inspect.inspect which messes things up badly. Commented Jul 17, 2013 at 21:20

1 Answer 1

4

In your program, the external value variable is being modified by the block. It is usual to assign nil to such external variables, but what you have will work fine.

Try modifying the value to something else inside the block, like this, and you will see that the variable is being changed. My guess is that output.empty? is coming up true.

value = nil
cmd_errors = Array.new

status = POpen4.popen4(cmd) do |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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.