On Tue, Nov 8, 2011 at 08:27, Fily S. [email protected] 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
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
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
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 C.'s voice so it was probably on The Ruby Show, but I don’t
think it was his blog, maybe Virtuous Code by Avdi G…
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.