60 507
Assignments Done
98,1%
Successfully Done
In April 2018

# Answer to Question #43424 in Ruby | Ruby on Rails for ermro

Question #43424
i have some doubts regarding OR EQUALS operator in ruby. how does ruby interpreter is implementing it.?
here is sample code
class C
def arr
@num ||= []
end
when we use or equals operator in this circumstance.first call to this method initializes it and added a element thats fine.how does it know when a second call to made to arr is done that array has one elemnt in it..
In Ruby, there are two values that are considered logical false. The first is the boolean value false, theother is nil. Anything which is non-nil andnot explicitly false is true. Thefirst time though the method, @num is nil,which is treated as false and the logical orportion of ||= needs to be evaluated and ends upassigning the empty array to @num. Since that&#039;s now non-nil, itequates to true. Since true || x is true no matter what x is, in future invocations Ruby short circuits the evaluation and doesn&#039;t do the assignment.Ingeneral terms x ||= y is equivalent to x = x || y, it&#039;s just shorthand. It&#039;s implemented as the expandedform, same as &amp;&amp;=, +=or -=.Thepattern is best described as a &quot;lazy initializer&quot;, that is thevariable is defined only once, but only when it&#039;s actually used. This is incontrast to an &quot;eager initializer&quot; that will do it as early aspossible, like inside the initialize method.You&#039;llsee other versions of this pattern, like:def arr   &nbsp; @num ||= begin   &nbsp;     stuff = [ ]   &nbsp;     # ...   &nbsp;    stuff&nbsp;&nbsp;&nbsp; end end&nbsp;This handles cases where theinitial value is not as trivial and may need some work to produce. Once again,it&#039;s only actually generated when the method is called for the first time.How does Ruby know on the secondpass to not initialize it again? Simple, by that point @num is already defined as something.As a note, if you&#039;re using valueslike false that wouldevaluate as non-true, then ||=will trigger every time. The only two logically false values in Ruby are nil and false, so most of the time this isn&#039;t an issue.You&#039;ll have to do this thelong-form way if you need to handle falseas well:&nbsp;def arr   &nbsp; return @num unless num.nil?    &nbsp; @num = false endThere was talk of adding an ||=-like operator that would only trigger on nil but I don&#039;t think that has been added to Ruby yet.

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!