16

Possible Duplicate:
What does ||= (or equals) mean in Ruby?
What does ||= mean?

I have just started learning RubyMotion and in a lot of examples I see the ||= syntax. What does this mean?

Here is an example:

def window
  @window ||= begin
    w = UIWindow.alloc.initWithFrame UIScreen.mainScreen.bounds
    w.rootViewController = @navigationController
    w
end

It is difficult to search symbols, google ignored the symbols in my query.

Community
  • 1
  • 1
Josh
  • 5,631
  • 1
  • 28
  • 54
  • 2
    Duplicate: [What does `||=` mean in Ruby?](http://StackOverflow.Com/q/995593/), [What does `||=` mean in Ruby?](http://StackOverflow.Com/q/3800957/), [what is `||=` in ruby?](http://StackOverflow.Com/q/3945711/), [Double Pipe Symbols in Ruby Variable Assignment?](http://StackOverflow.Com/q/4500375/), [What does the “`||=`” operand stand for in ruby](http://StackOverflow.Com/q/5124930/), [what does a `||=` mean in Ruby language?](http://StackOverflow.Com/q/5230162/), [Is the ruby operator `||=` intelligent?](http://StackOverflow.Com/q/2989862/), … – Jörg W Mittag Jul 21 '12 at 10:38
  • … [What does `||=` mean?](http://StackOverflow.Com/q/7556902/), [What does “`||=`” do in Ruby 1.9.2?](http://StackOverflow.Com/q/7714803/) ['`||=`' operator in Ruby](http://StackOverflow.Com/q/8506257/), [What does the '`||=`' operator do in ruby?](http://StackOverflow.Com/q/9698946/), [How does “`||=`” work?](http://StackOverflow.Com/q/11123385/), and probably many others as well. See also [The definitive list of `||=` (OR Equal) threads and pages](http://Ruby-Forum.Com/topic/151660/). – Jörg W Mittag Jul 21 '12 at 10:39
  • 2
    Use symbolhound.com to search for symbols. – Andrew Grimm Jul 23 '12 at 23:16
  • @JörgWMittag Why do you list all the duplicates? – Andrew Grimm Jul 23 '12 at 23:23

2 Answers2

34

It is an assignment operator which means: or assign this value to a variable.

So if you did something like x ||= ythis meansx || x = y so if x is nil or false set x to be the value of y.

ewein
  • 2,695
  • 6
  • 36
  • 54
  • I was looking at the link @Marc B posted above under "Conditional assignment." – jrdioko Jul 20 '12 at 21:31
  • 1
    well its essentially the same thing. If you are doing x = x || y, if as long as the left operand return false the right operand will be evaluated. In the case you use x ||= y, if x is false x gets y and x = x|| y, if x != x (false) x gets y. – ewein Jul 20 '12 at 21:34
  • Were you aware that this was a duplicate question when you answered it? – Andrew Grimm Jul 23 '12 at 23:27
  • No, I did not know it was a duplicate. – ewein Jul 24 '12 at 03:54
4

This Operator only sets the variable if the variable is false or Nil.

musicmatze
  • 4,124
  • 7
  • 33
  • 48