On Mon, Jan 24, 2011 at 7:18 PM, Jon Leighton <j / jonathanleighton.com> wrote:
> Thanks for the explanation. FWIW I think it is a shame that postfix
> conditionals are semantically different to normal ones, but it's good to
> know why the difference occurs.

See Gary's reply.

> I started to wonder about this when I was using the following code:
>
> bla(foo) if foo = self.foo
>
> In other words, I was trying to put the value of the method foo into the
> local variable foo in order to avoid calling the method twice. To me the
> above is quite an elegant way of doing that, so it's a shame that it
> does not actually have the intended effect ;) [it all came crashing down
> when I renamed the foo variable]

Frankly, I don't find this elegant at all.  There is only one
situation where it is reasonable and elegant to place an assignment in
a conditional expression: in case of loops where the expression
changes but the result needs to be reused after the condition, e.g.

while (now = Time.now) < target_time
  puts "We have now #{now}"
  do_more_work
  log.debug "Work for timestamp : #{now}"
end

For all other situations, i.e. if it is a non loop condition, the
expression does not change or is not used inside the body or
afterwards, there is no point at all to assign in the conditional
expression.  Your aim to avoid calling self.foo twice is easily
reached without assignment inside the condition:

# traditional, easy to understand
f = foo
bla(f) if f

or

# slightly more involved but elegant
f = foo and bla(f)

The latter makes up for quite an elegant solution which also has the
advantage that it is executed in the same order as it is read by a
human being (at least in many cultures); even for others the execution
order is the same as for other sequences of statements.

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/