From: Robert Klemme Date: 2007-12-21T16:50:57+09:00 Subject: Re: Using 'when' as a statement modifier 2007/12/19, MonkeeSage : > On Dec 17, 10:31 pm, Tom Agnew wrote: > > Hello all, > > > > I have a suggestion for an enhancement that could add to the readability > > of my programs. > > > > I'm a frequent user of 'if' and 'unless' statement modifiers. It's a > > beautiful abbreviation that enhances the readability of my code. > > > > Here is a pattern that I use from time to time: > > > > result = func(x) unless func(x)==y > > > > This has the potential to invoke func(x) twice in some implementations. > > > > It occurred to me that the 'case' semantics could be borrowed to create > > a useful new modifier. Here's a suggestion that might be more efficient > > and possibly more readable: > > > > result = func(x) when result==y Note, that this does not seem to be the same as above and can be replaced by result = y if func(x) == y This has the negative effect that it will change semantics of assignment which is bad IMHO. If I understand you properly then the code above with "when" should do something like __tmp_1 = func(x) result = __tmp_1 if __tmp_1 == y .i.e. assignment is done only after a successful test. Personally I don't mind to write it exactly like that (with different name for __tmp_1 probably). Because it's totally obvious what happens here. You could even write a method to do that for you def choose(val, test, fallback) val == test ? val : fallback end def except(val, test, fallback) val == test ? fallback : val end # ... result = except func(x), y, result Kind regards robert -- use.inject do |as, often| as.you_can - without end