1

I'm still pretty green when it comes to Ruby and am trying to figure out what this is doing:

 command_windows.each {|window| window.hidden ||= window.open?  } 

The command_windows variable appears to be an array of objects. If someone could explain to me what this line of code means, particularly what the ||= symbol is I would appreciate it.

user2864740
  • 60,010
  • 15
  • 145
  • 220
Mir
  • 305
  • 8
  • 24

2 Answers2

4

foo ||= "bar" is the equivalent of doing foo || foo = "bar".

As Mischa explained, it checks for a falsy value before assigning.

In your case, you could think of it as:

command_windows.each {|window| window.hidden || window.hidden = window.open?  }

which is another way of saying

command_windows.each {|window| window.hidden = window.open? unless window.hidden }
tonchis
  • 598
  • 3
  • 10
2

The ||= operator is used to assign new value to variable. If something was assigned to it before it won't work. It is usually used in hashes, so you don't have to check, if something is already assigned.

Mischa
  • 42,876
  • 8
  • 99
  • 111
Tomasz Kal
  • 119
  • 9
  • Ok, so if my understanding is correct, each object in the array is being looped through and identified as a variable called "window." If the window element's "hidden" attribute is false then the attribute is set to whatever the value of window.open is (either true or false). – Mir May 24 '15 at 23:02
  • @Mir: if it's `false` or `nil` then `window.hidden` will be set to `window.open?` – Mischa May 24 '15 at 23:36
  • 1
    It's about whether the variable is *falsy* or undefined. E.g. in the case of `foo = false` and `foo ||= 'bar'` then `foo` will be `'bar'` even though something was already assigned to it. – Mischa May 24 '15 at 23:44