-3

The following code snippet fully describes the problem, but I have to type all these extra words in to get SO to let me post it.

some_var ||= some_other_var do
   # Does this run every time, or only sometimes?
   stuff
end
Throw Away Account
  • 2,593
  • 18
  • 21

1 Answers1

1

Such code will be evaluated just like any other with a ||= operator. If some_var is nil or false the function will run and return value will be assigned to some_var; otherwise the value of some_var will be returned. See What does ||= (or-equals) mean in Ruby? for reference.

Community
  • 1
  • 1
xlts
  • 136
  • 5
  • But what about the block? I found some code that puts a block after the assignment (as shown in my example), which makes absolutely no sense and isn't documented in any place that I know of. AFAIK, it should be a syntax error. In fact, the question you linked to has no answers that discuss putting a block after the `||=` assignment. – Throw Away Account May 09 '17 at 22:28
  • The block is simply a "special type of argument" passed to a method (in your example the method is `some_other_var`); you don't pass a block to a variable. The method with a passed block will be evaluated and its return value will be assigned to `some_var`. – xlts May 09 '17 at 22:37
  • Damn Ruby and its confusing syntax! I failed to remember that `some_other_var` can actually be a method call. Thanks. – Throw Away Account May 09 '17 at 22:41