? and :
While refactoring my old code I came across some methods to shorten simple if else statements. I saw a lot of code online using ? with : to create short one liners but until recently I wasn’t 100% how these worked. I knew that you could use ? to indicate a boolean with methods such as include? but how does this work with :???.
The colon used with a question mark allows you to create a simple if else statement. You write what you want to check before the question mark and write the code body for true on the left of the colon and on the right for false. In this way you can shorten a simple if else statement.
test = true
test ? "true":"false"
==> "true"
test = false
test ? "true":"false"
==> "false"In Javascript the logical check works for anything that can be tested a truthy value such as the existence of an argument within a function. (this doesn’t work in Ruby).
def test(n)
n ? "argument is #{n}":"no argument"
endtest(1) ==> argument is 1
test() ==> no argument