On Tue, Nov 8, 2011 at 08:27, Fily Salas <fs_tigre / hotmail.com> wrote:
> Can someone explain the use of double pipes "||" in Ruby?
It's the logical "or" operator.
> Are these part of blocks only?
The pipes that surround block arguments are a different beastie entirely.
> Where else can double pipes be used?
Mainly in combining boolean values. Say you want to do something if
some number is *not* in the positive two-digit range (leading zeroes
don't count). You would do:
if mynum < 10 || mynum > 100
# do whatever
end
> The way I understand it, is basically for adding temporary variables to
> help identify items in an array, other than that I'm not sure
> where else can they be used.
That's not the main usage, it's just a handy trick. When you see the
construction:
arr[x] ||= y
what that's really saying is "evaluate arr[x], and if that's false
(which could be either the actual boolean value of false, or it could
be nil, such as if no value was assigned there), put y there, else
leave it alone". Despite the usual meaning of tacking an = sign onto
any operator, it's not *quite* equivalent to:
arr[x] = arr[x] || y
which *will perform an assignment* in either case. The previous one
will not, if arr[x] already had a (non-false) value. IIRC, one of the
popular Ruby podcasts recently covered a recent post about this on one
of the popular Ruby blogs. In trying to remember it I'm hearing it in
Peter Cooper's voice so it was probably on The Ruby Show, but I don't
think it was his blog, maybe Virtuous Code by Avdi Grimm.
Alternately you might see:
x = y || z
This *could* be boolean math, or it could be "if y is not false (or
nil) assign it to x, else assign z to x".
You might be getting confused because Ruby also has "and" and "or"
keywords, but these are subtly different, suitable *only* for use in
boolean manipulation, and usually better off forgotten.
-Dave
--
LOOKING FOR WORK! What: Ruby (on/off Rails), Python, other modern languages.
Where: Northern Virginia, Washington DC (near Orange Line), and remote work.
See: davearonson.com (main) * codosaur.us (code) * dare2xl.com (excellence).
Specialization is for insects. (Heinlein) - Have Pun, Will Babble! (Aronson)