Aurimas Aurimas - 4 months ago 20
Ruby Question

Ruby equivalent to JavaScript operator `||`

How can this be achieved in Ruby? Can it be done without repeating the variable?
Javascript:

b = a || 7


This assigns
a
if
a
is not
0
and
7
otherwise

One specific case is converting date.wday to 7 if it returns 0 (Sunday).

Answer

Just out of curiosity:

class Object
  def javascript_or?(other)
    (is_a?(FalseClass) || nil? || '' == self || 0 == self) ? nil : self
  end
end

and:

a = b.javascript_or?(7)