# bank accounts using closures in ruby # Ruby variables: lower case are local, upper-case are global. So in order # to have nested scope, we need to have nested lambda-expressions. # Here's a basic boolean toggle: def toggle() val = true # initial value lambda{ val = !val; val } end t = toggle() t[] # returns false t[] # returns true ### bank accounts. ## instead of a series of if-else statements or 'cond', I will use a ## Ruby hash table to store the fields of the "object" def newaccount(bal) # accounts are created with initial balance # a "private" method to chare a 5% fee for withdraws. chargefee = lambda {|x| bal = bal - (x/20.0)} # return the following hash table: { "inquiry" => lambda { bal }, "withdraw" => lambda {|x| if bal>=x then bal -= x end; chargefee[x]}, "deposit" => lambda {|x| if x>0 then bal += x end}, "compareTo" => lambda{|other| bal - other["inquiry"][]} } end #newaccount ## Note that the "interface" returned by the newaccount function is a closure ## involving bal, the account balance. Unlike in scheme, the interface takes ## the form of a hash table. We could use a lambda like in scheme, but ## a hash table more effectively implements this kind of a "function". Myaccount = newaccount(100) Youraccount = newaccount(200) Myaccount["withdraw"][30] # myaccount.withdraw(30); Youraccount["deposit"][50] puts Myaccount["inquiry"][] puts Myaccount["compareTo"][Youraccount] ## note to change the default value returned by a hash table, initialize with ## h = Hash.new("don't know")