1

I have the following closure:

def func
  def inner_func
    list << 3 # how to append an element to the outer `list`?
  end

  list = []
  inner_func
  list
end

I am not sure how I can append something to list from inner_func, as the above attempt is wrong.

sawa
  • 165,429
  • 45
  • 277
  • 381
linkyndy
  • 17,038
  • 20
  • 114
  • 194
  • 1
    Problem with Ruby is that it _looks_ like it supports nested methods, but it doesn't, as pointed out by Piotr. You could use eg. Procs though, as indicated in http://www.elonflegenheimer.com/2012/07/08/understanding-ruby-closures.html – EdvardM Jun 26 '15 at 12:45
  • I understand. Get you point how to use procs in my case? Also, `inner_func` is actually a whole lot bigger, is it right to stuff everything inside a proc? – linkyndy Jun 26 '15 at 12:48

2 Answers2

2

Use instance methods, like this:

def func
  def inner_func
    @list << 3 # how to append an element to the outer `list`?
  end

  @list = []
  inner_func
  @list
end

However take a look at this - regarding Ruby and nested methods.

Example of a clean workaround:

def func
  list = []
  inner_func list # => [3]
  inner_func list # => [3, 3]
end

def inner_func(list)
  list << 3
end
Community
  • 1
  • 1
Piotr Kruczek
  • 2,384
  • 11
  • 18
2

Ruby does not have nested methods. It does have lambda's, which happen to be closures.

def func
  list = []
  l = ->{ list << 3}
  l.call
  p list
end

func # => [3]
steenslag
  • 79,051
  • 16
  • 138
  • 171