Search code examples
rubyoperatorsequals

doubts regarding "||=" OR EQUALS operator in ruby


I have some doubts regarding OR EQUALS (||=) operator in ruby. How does ruby interpreter implement it? Here is a sample of code:

class C
  def arr
    @num ||= []
  end
end

When we use OR EQUALS operator in this circumstances, the first call to this method initializes the variable and adds an element, that's fine. When a second call is made to arr, how does it know that array has one element in it..


Solution

  • In Ruby, there are two values that are considered logical false. The first is the boolean value false, the other is nil. Anything which is non-nil and not explicitly false is true. The first time though the method, @num is nil, which is treated as false and the logical or portion of ||= needs to be evaluated and ends up assigning the empty array to @num. Since that's now non-nil, it equates to true. Since true || x is true no matter what x is, in future invocations Ruby short circuits the evaluation and doesn't do the assignment.