From: Siddharth Reddy Date: 2011-09-29T03:23:51+09:00 Subject: Re: Ruby Syntax @keywords ||= [ ] --0015174413324de21904ae047e1f Content-Type: text/plain; charset=ISO-8859-1 Awesome ! this should clear my doubts.. On Wed, Sep 28, 2011 at 11:48 PM, Dave Aronson < rubytalk2dave@davearonson.com> wrote: > On Wed, Sep 28, 2011 at 13:07, Bhavesh Sharma > wrote: > > > Sorry if this comes across as a dumb question, but what does the > > following syntax mean in ruby. > > > > @keywords ||= [] > > > > I understand that its setting the instance variable as an array but what > > is the logical operator '||' doing in there. > > "x ||= y" is a common idiom for "if x is nil, set it to y". > > An operator followed by the = sign is like saying "use the thing on > the left, as the left side of the operator". In other words, the > above is equal to: > > @keywords = @keywords || [] > > Similarly, "x += 1" is equal to "x = x + 1", and so on for all other > operators. > > The || operator specifically won't bother evaluating its right-side > operator, if the left is true. In Ruby, two things are not true: > false, and nil. So, if the thing on the left is nil (or boolean > false), it gets the value on the right, else it gets left alone. > > -Dave > > -- > LOOKING FOR WORK, preferably Ruby on Rails, in NoVa/DC; see main web site. > Main Web Site: davearonson.com > Programming Blog: codosaur.us > Excellence Blog: dare2xl.com > > --0015174413324de21904ae047e1f--