Jim Weirich wrote: > Sam Kong wrote: > > Hi! > > > > A friend of mine challenged me with Smalltalk. > > He's a big fan of Smalltalk. > > He asked me what I can do if I want to add "try ~ finally ~" systax in > > Ruby. > > Yes, we already have "begin ~ ensure ~". > > But he asked me whether Ruby is flexible enough to extend such a thing > > without changing the language itself. > > He said that Smalltalk doesn't have "try ~ finally ~" in the language > > but can be defined without changing the language. > > > > Personally, I don't think such flexibility is really needed. > > However, I want to defend Ruby. > > How would you react such an attack? > > There are several ways this could be done ... here is one: > > class TryFinally > def initialize(block) > @block = block > end > def finally > @block.call > ensure > yield > end > end > > def try(&block) > TryFinally.new(block) > end > > Usage: > > try { > puts "Trying" > fail "oops" > }.finally { > puts "Always printed" > } > > It is a bit little easier in Smalltalk because of the use of keywords in > an argument list, but still quite doable in Ruby. This is nice. But my intention is not to make a new syntax that does the same thing. Let's assume that there's no *ensure* syntax in Ruby. Sam