Home > Blockchain >  Ruby // Operators ~ A ||= (B || C)
Ruby // Operators ~ A ||= (B || C)

Time:04-09

Is there a way to write with operators the following:

if A is true
  then A = A
elsif if B is true
  then A = B
else
  A = C
end

Only B or C will have a value at any given time. Sometimes A will have a value sometimes not.

I was thinking something like A ||= (B || C) but I am getting some strange actions as a result.

Thank you.

CodePudding user response:

You can write

Module.const_defined?(:A) ? A : (B == true ? B : C)

to obtain the value of A.

A not defined
B = true
Module.const_defined?(:A) ? A : (B == true ? B : C)
  #=> true
A not defined
B = false
Module.const_defined?(:A) ? A : (B == true ? B : C)
  #=> 42
A = "cat"
B = false
C = 42
Module.const_defined?(:A) ? A : (B == true ? B : C)
  #=> "cat"

See Module#const_defined?.

CodePudding user response:

Constants and local variables will raise NameError if not defined. You probably want to use instance variables instead, as they are auto-vivified as nil when referenced even if they haven't been assigned to yet. For example:

@a ||= (@b || @c)
#=> nil

If either @a or @b are truthy, then things will probably work as you expect. However, if all three variables are falsey, then @a will be assigned the value of @c even if @c evaluates as nil or false.

  • Related