1

In my readings about structuring methods with options hashes for ruby, I've run into a coding "motif" a few times that I can't explain. Since I don't know what it's called, I'm having a lot of difficulty looking it up to learn more about it.

Here's an example:

1  def example_method(input1, options={})
2 
3     default_options = {
4         :otherwise => "blue",
5         :be_nil => nil
6       }
7 
8     options[:be_nil] ||= options[:otherwise]
9 
10    # other code goes down here
11  end

So above, on line 8, you can see what I'm talking about. From what I can put together, the line of code acts similarly to a tertiary operator. Under one condition, it sets a variable to one value... under a different condition, it sets the variable to a different value. In this case, however, the code updates a hash that's stored in the "options" variable. Is that a correct assumption? Furthermore, what is this style/operator/functionality called?

elersong
  • 756
  • 4
  • 12
  • 29
  • While I can't answer your question, the C-style operator you're referring to is a _[Ternary operator](http://en.wikipedia.org/wiki/Ternary_operation)_ - not _tertiary_ ;) – Adam S Mar 03 '14 at 20:16
  • http://stackoverflow.com/questions/995593/what-does-or-equals-mean-in-ruby – Rafa Paez Mar 03 '14 at 20:16
  • Thanks @AdamS, I mess up terminology from time to time. – elersong Mar 03 '14 at 20:21
  • And thanks for pointing out the duplicate! I was pulling hair trying to find similarities since google only searches alphanumerics! – elersong Mar 03 '14 at 20:23

1 Answers1

0

THis is a conditional assignment. The variable on the left will be assigned a value if it is nil or false. This is the short for of saying:

unless options[:be_nil]
  options[:be_nil] = options[:otherwise]
end
Nik O'Lai
  • 3,586
  • 1
  • 15
  • 17