Ad
  • Custom User Avatar

    It means the value will only be replaced if it is nil or false. (Correct me if I'm wrong please, I'm also new)

    #Case 1:
    a = 1
    a ||= 10
    print a #=> 1

    #Case 2:
    a = nil
    a ||= 10
    print a #=> 10

    a||= 10 is logically equivalent to: a || a = 10

    Let's understand that behaviour. When we put together many or's:
    a || b || c || d, it will return true immediatly when the first true value is found.
    So in the example above, if 'a' is true, then b, c and d WON'T be evaluated by the or operator.

    The same happens here: a || a = 10.

    if a is false (or nil) it will evaluate (a = 10) which then changes the value of a.
    if a is true (or != nil), then (a = 10) WON'T be evaluated at all.

  • Custom User Avatar

    Hello, I'm new to Ruby and was wondering what ||= does. Would anyone be able o explain the above code and how it works? Thanks!