0

In this snippet of previously written code, there are ? and a : used by themselves (lone symbols), and not appended onto a word. What do they mean in this instance?

  # Fill application object with applicant info; generic info if not provided.
  availability ? formdata[:availability] = availability : (formdata[:availability] = [0,1,2,3,4,5,6])
AA.
  • 31
  • 6
  • 2
    FWIW that line could be rewritten without the ternary thus: `formdata[:availability] = availability || [0,1,2,3,4,5,6]` – Pavling Jan 13 '20 at 19:29

1 Answers1

1

This is the ternary operator. It is the equivalent of an if/else. Your code could alternatively be written like this:

if availability 
  formdata[:availability] = availability 
else
  (formdata[:availability] = [0,1,2,3,4,5,6])
end

I would also argue that it should be simplified to something like this instead:

formdata[:availability] = availability ? availability : [0,1,2,3,4,5,6]

The assignment in the conditionals is an odd way of writing that, and not common.

You could also simplify this further to:

formdata[:availability] = availability || [0,1,2,3,4,5,6]

The details of how an || (or) assignment operates can be found here

Gavin Miller
  • 42,055
  • 20
  • 117
  • 184
  • thank you! i wasnt aware that you can write if else statements like this – AA. Jan 13 '20 at 19:12
  • 1
    @AA. many (most?) languages have a ternary operator. – Gavin Miller Jan 13 '20 at 19:13
  • @GavinMiller: "many (most?) languages have a ternary operator." - it's becoming less and less common, I find. Go and Rust don't have it, for example – Sergio Tulentsev Jan 13 '20 at 19:14
  • why do people use ternary operators instead of if else statements or case statements? is it because of simplicitiy or flexibility? i am still learning new things to coding so forgive my questions. the ternary operator seems a little hard to read at first glance, hence my initial question. – AA. Jan 13 '20 at 19:16
  • 1
    @AA.: it's not too hard to read, if it's used correctly/responsibly. In the snippet from your post, it was misused. – Sergio Tulentsev Jan 13 '20 at 19:20