On 24 May 2012 13:05, botp <botpena / gmail.com> wrote:
> Hi All,
> am looking for a ruby idiom on the ff
>
> # some code here....
> r=3Dfoo
> return r if r
> # some code here..
>
> tried it w
>
> return r if (r=3Dfoo)
>
> but ruby complains w undefined r
> so ended up w
>
> if r=3Dfoo
> =A0return r
> end
>
> would be nice if modifiers can act like normal if

You can force it into one line in various ways if that's what you
want. For example:

  if a=3Dfoo then return a; end

Or if you want something more arbitrarily idiomatic you could use
something like:

  (a =3D foo) && (return a)

However that's pretty ugly.  If you want human-parseable code you're
probably better off with something like:

  def get_something
    # ...
    if most_likely_answer =3D foo
      return most_likely_answer
    end
    # ... more expensive tests
  end

...because at least then it's clear why you're making the
short-circuit branch.  And if you want to use the result of `foo`
after the if-branch it's definitely clearer if you do the assignment
explicitly beforehand:

  def get_something
    # ...
    possible_answer =3D foo
    # ...
    if possible_answer
      return possible_answer
    end
    # ...
    possible_answer +=3D 7
  end

The reason `return a if a=3Dfoo` doesn't work is because of scope.  I
looked it up once many moons ago but can't remember the details
anymore. Perhaps someone who understands the parse tree can help.

--=20
=A0 Matthew Kerwin, B.Sc (CompSci) (Hons)
=A0 http://matthew.kerwin.net.au/
=A0 ABN: 59-013-727-651

=A0 "You'll never find a programming language that frees
=A0 you from the burden of clarifying your ideas." - xkcd