The conditional operator in Ruby

来源:互联网 时间:1970-01-01

The official name of the ? :operator is the conditional operator, though most people know it as the ternary operatorindicating the number of operands it has.

There are several unary operatorsthat handle a single operand. For example -can be unary operator.

Most of the operators ad binary operatorsthat handle two operands. For example *always needs two operands to work on, but in most cases -is also used as a binary operatory.

There is only one ternary operator, that has 3 operands. It is called the conditional operator, but because it is the only one with 3 operands, most of the people call it the ternary operator.

Conditional Operator in Ruby

In general it looks like this:


It evaluates the CONDITION. If it is truethen the code evaluates the part between ?and :and returns the result. If the CONDITIONis false, then the middle part is skipped and the 3rd part is evaluated and the result of that expression is returned.

Example puts

In this example the return value of the conditional operator is passed to puts

filename = ARGV.shiftputs filename ? filename : 'No file given' Example smaller

In this example we check whihc one of the two random values is smaller and return that one:


x = rand()y = rand()puts xputs y smaller = x < y ? x : y;puts smaller