Ruby의 closure 예제 #2

Tags:

앞서의 글(Ruby의 closure 예제) 은 거의 블럭 사용에 가까웠습니다. 하지만 closure의 정의는 원래 그게 아니므로….

irb(main):001:0> def stack_closure
irb(main):002:1>   stack = []
irb(main):003:1>   push = lambda {|x| stack.push(x)}
irb(main):004:1>   pop = lambda {stack.pop}
irb(main):005:1>   top = lambda {stack[-1]}
irb(main):006:1>   return push, pop, top
irb(main):007:1> end
=> nil
irb(main):008:0> push, pop, top = stack_closure()
=> [#<Proc:0xb7f183b0@(irb):3>, #<Proc:0xb7f180e0@(irb):4>, #<Proc:0xb7f17e38@(irb):5>]
irb(main):009:0> push.call(10)
=> [10]
irb(main):010:0> push.call(20)
=> [10, 20]
irb(main):011:0> pop.call
=> 20
irb(main):012:0> top.call
=> 10

Matz의 OSCON2005 자료에 나온 좋은 예제여서 올립니다.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *