I’ve been using Ruby/Rails for about about four months and wonder what
the the Ruby alternative to the popular C/C++ idiom of setting and
testing a variable in the condition of an ‘if’ statement. If C/C++ the
usage is typically:
if ((ptr = fcn_returning_ptr(...)) == NULL) {
val = ptr->ref
} else {
val = DEFAULT
}
or the compact version:
val = (ptr = fcn_returning_ptr(...)) ? ptr->ref : DEFAULT
Which, when I translate to Ruby yields (ActiveRecord example):
unless (ar = Model.find(...)).nil?
val = ar.attribute
else
val = DEFAULT
or the equivalent expression.
It seems to me that this is very unRuby-like and I don’t see any similar
usages in any of the code-bases in which I have looked.
I know – I just omitted it for the sake of brevity. Do you have any
thoughts about a better, or my ruby-like technique?
Actually I suck at these kinds of stylistic questions. If I want
somebody else (where “somebody else” includes “me, after a few months
when I’ve forgotten what I was doing”) to be able to easily understand
my code I use the “long” version with no short-cuts. If it’s just for me
I stick with the first thing that works.