1

I have a scenario

func1 do 
  x='abc'
  func2 do
    puts x
  end
end

for this I get x = nil. Why is it so, and how to access external variable like x in inner block.

3
  • 4
    What is func2? It depends on that. If it is an iterator, x should not return nil. Commented Aug 24, 2013 at 6:52
  • 2
    sawa is right. For example, this: Object.new.tap { x='abc'; [Object.new].each { puts x } } outputs abc. Commented Aug 24, 2013 at 6:56
  • 1
    func1 & func2 are originate & record function of rubydoc.info/gems/adhearsion/frames. x is locally defined Commented Aug 24, 2013 at 7:17

1 Answer 1

1

You will get "abc" only if func1 and func2 executes blocks you are passing to them (yielding or calling).

Check out an example

def func1
end

def func2
end

func1 do
  x = "Hello World"
  func2 do
    puts x
  end
end
#=> nil

def func3
  yield
end

def func4
  yield
end

func3 do
  x = "Hello World"
  func4 do
    puts x
  end
end
#=> Hello World
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.