From: Alan Johnson Date: 2008-11-26T09:10:51+09:00 Subject: Re: Begin else pattern question On Tue, Nov 25, 2008 at 3:19 PM, Mikel Lindsaar wrote: > What is the cleanest way of doing: > def initialize(value) > begin > if value == 'blah' > a_action > else > b_action > end > rescue > b_action > end > end > > That is. If a is needed and doing a throws an exception, do b instead. > Otherwise, if a is not needed do b. > > Or is that the cleanest way? > > By cleanest, I mean l don't like calling b_action twice in the method if I > don't have to, but it's a trade off on readability... and I don't _like_ the > way the code looks now :) > > Any other simpler way to do this pattern? > > Mikel > A device that turns exceptions into a return value might assist. Perhaps something like this: def succeeded begin yield true rescue false end end def a_action(succeed) raise "failed" if !succeed print "a_action\n" end def b_action print "b_action\n" end def action(value, succeed) b_action if !(value == "blah" && succeeded { a_action(succeed) }) end action "blah", true action "blah", false action "not blah", true action "not blah", false -- Alan