Hi,

I guess i'm missing the point.  could you enlighten me why it needs to
use closure?

At Wed, 29 Nov 2000 20:16:55 +0900,
peter.wood / worldonline.dk wrote:

> I am trying to figure out how to do closures in Ruby. In CL I can do
> this :
> -------------------------------------------------------
> (defun shop-list (the-list)
>   #'(lambda (action item)
>       (case action
> 	(buy (setf the-list (adjoin item the-list)))
> 	(cancel (setf the-list (remove item the-list)))
> 	(see the-list))))
> 
> ---------------------------------------------------------

this can be:

class Array
  def adjoin(item)
    self.push item unless self.include? item
  end
end

class ShopList
  def initialize(shop_list = [])
    @the_list = shop_list
  end

  def buy(item)
    @the_list.adjoin item
  end

  def cancel(item)
    @the_list.remove item
  end

  def see
    @the_list
  end
end


> And use it like this:

if __FILE__ == $0
  week1 = ShopList.new([])
  week1.buy 'cornflakes'
  week1.buy 'potatoes'
  week1.buy 'cornflakes'
  p week1.see #=> ["cornflakes", "potatoes"]

  week2 = ShopList.new([])
  week2.buy 'beer'
  p week2.see #=> ["beer"]
end


------ 8< -------  or ------ 8< -------

  
def shop_list(the_list)
  Proc.new {|args|         # can't do  Proc{|action, item=nil|
    @the_list = the_list
    case args
    when Array             # so it's got complicated... :(
      action = args.shift
      case action
      when :buy
	@the_list.push args.pop
      when :cancle
	@the_list.remove args.pop
      end
    else
      if args == :see
	@the_list
      end
    end
  }
end

if __FILE__ == $0
  week1 = shop_list([])
  week1.call :buy, 'cornflakes'
  week1.call :buy, 'potatoes'
  p week1.call :see
end
--
        yashi