Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

Ruby accessing outer variables in nested function

I'm sure there's a simple answer for this; I just can't seem to find it. I made a nested function in Ruby, and I was having trouble accessing variables from the outer function inside the inner function:

def foo(x)
  def bar
    puts x
  end
  bar
  42
end

foo(5)

I get: NameError: undefined local variable or methodx' for main:Object`

The analogous Python code works:

def foo(x):
  def bar():
    print x
  bar()
  return 42

foo(5)

So how do I do the same thing in Ruby?

question from:https://stackoverflow.com/questions/1016408/ruby-accessing-outer-variables-in-nested-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As far as I know, defining a named function within a function does not give you access to any local variables.

What you can do instead is use a Proc:

def foo(x)
  bar = lambda do
    puts x
  end
  bar.call
  42
end

foo(5)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...