From: Matthew Kerwin Date: 2012-05-24T12:38:38+09:00 Subject: Re: looking for a ruby idiom : r=foo; return r if r On 24 May 2012 13:05, botp wrote: > Hi All, > am looking for a ruby idiom on the ff > > # some code here.... > r=foo > return r if r > # some code here.. > > tried it w > > return r if (r=foo) > > but ruby complains w undefined r > so ended up w > > if r=foo >  return 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=foo then return a; end Or if you want something more arbitrarily idiomatic you could use something like: (a = 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 = 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 = foo # ... if possible_answer return possible_answer end # ... possible_answer += 7 end The reason `return a if a=foo` 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. --   Matthew Kerwin, B.Sc (CompSci) (Hons)   http://matthew.kerwin.net.au/   ABN: 59-013-727-651   "You'll never find a programming language that frees   you from the burden of clarifying your ideas." - xkcd