On 6/12/05, Robert Klemme <bob.news / gmx.net> wrote:
> Gavin Kistner <gavin / refinery.com> wrote:
> > On Jun 11, 2005, at 11:03 AM, Douglas Livingstone wrote:
> >> On 6/11/05, Gavin Kistner <gavin / refinery.com> wrote:
> >>> If I write code like this:
> >>>    self.foo.bar if self.foo
> >>> then ruby runs the #foo method twice. (Javascript is the same way.)
> >>
> >> I'd probably go for:
> >>
> >> result = foo
> >> result.bar unless result.nil?
> >>
> >> If it has to go one one line, could be:
> >>
> >> t = foo and puts t.bar
> >
> > So you've added 1-2 more options to my list, but the intent of my
> > post was not how to rewrite it differently, but to request  that
> > perhaps the parser could be a little more extra-intelligent about
> > determining the scope/guaranteed presence of the local variable.
> 
> Why change the parser if there are ways to do this that don't require such
> heavy language modifications?

IMHO, it wouldn't be a "heavy language modification" (irrespective of
the work required). I've always felt uncomfortable with the fact that
an assignment in a statement modifier doesn't show up for the
statement it is modifying, even though it is executed first. I feel
the following two examples should be equivalent:

  if t = foo
    t.bar
  end

-- and:

  t.bar if t = foo

I know I've tried variations on the previous before many times,
forgetting that it doesn't work. I end up settling for the "t = foo
and t.bar", which doesn't read as clearly to me.

cheers,
Mark

> Btw, here's another option if you need that pattern more often
> 
> class Dummy
>   def method_missing(*a,&b) self end
> end
> DUMMY = Dummy.new
> 
> (foo || DUMMY).bar
> 
> Apart from that I'd go with the "and" variant:
> 
> tmp = foo and tmp.bar
> 
> Kind regards
> 
>     robert
> 
> 
>