How do I use the conditional operator (? :) in Ruby?

How do I use the conditional operator (? :) in Ruby?

ruby ternary operator multiple statements
ruby ternary operator nil
ruby ternary nil
ruby conditional assignment
rails ternary operator in view
how to use else in ruby
ruby operators cheat sheet
ruby multiple assignment in conditional

How is the conditional operator (? :) used in Ruby?

For example, is this correct?

<% question = question.size > 20 ? question.question.slice(0, 20)+"..." : question.question %>

It is the ternary operator, and it works like in C (the parenthesis are not required). It's an expression that works like:

if_this_is_a_true_value ? then_the_result_is_this : else_it_is_this

However, in Ruby, if is also an expression so: if a then b else c end === a ? b : c, except for precedence issues. Both are expressions.


puts (if 1 then 2 else 3 end) # => 2

puts 1 ? 2 : 3                # => 2

x = if 1 then 2 else 3 end
puts x                        # => 2

Note that in the first case parenthesis are required (otherwise Ruby is confused because it thinks it is puts if 1 with some extra junk after it), but they are not required in the last case as said issue does not arise.

You can use the "long-if" form for readability on multiple lines:

question = if question.size > 20 then
  question.slice(0, 20) + "..."

How to Use The Ruby Ternary Operator (?:), A ternary operator is made of three parts, that's where the word “ternary” comes from. These parts Duration: 4:27 Posted: Oct 1, 2019 The ternary (or conditional) operator will evaluate an expression and return one value if it's true, and another value if it's false. It's a bit like a shorthand, compact if statement. It's a bit like a shorthand, compact if statement.

puts true ? "true" : "false"
=> "true"

puts false ? "true" : "false"
=> "false"

Ruby Ternary operator, Ternary operator logic uses "(condition) ? (true return value) : (false return value)" statements to shorten your if/else structures. It first evaluates  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: CONDITION ? EVALUATE_IF_CONDITION_WAS_TRUE : EVALUATE_IF_CONDITION_WAS_FALSE

Your use of ERB suggests that you are in Rails. If so, then consider truncate, a built-in helper which will do the job for you:

<% question = truncate(question, :length=>30) %>

What is the ternary operator in Ruby?, first evaluates for a true or false value and then, depending upon the result of the evaluation, executes one of the two given statements​. Complex Ternary Operators. The ternary operator can be used incorrectly. It starts to become a bad idea whenever you want to do something complex with it. For example: You can assign the result of a ternary expression to a variable. a = 10 > 5 ? "yes" : "no" That’s fine.

@pst gave a great answer, but I'd like to mention that in Ruby the ternary operator is written on one line to be syntactically correct, unlike Perl and C where we can write it on multiple lines:

(true) ? 1 : 0

Normally Ruby will raise an error if you attempt to split it across multiple lines, but you can use the \ line-continuation symbol at the end of a line and Ruby will be happy:

(true)   \
  ? 1    \
  : 0

This is a simple example, but it can be very useful when dealing with longer lines as it keeps the code nicely laid out.

It's also possible to use the ternary without the line-continuation characters by putting the operators last on the line, but I don't like or recommend it:

(true) ?
  1 :

I think that leads to really hard to read code as the conditional test and/or results get longer.

I've read comments saying not to use the ternary operator because it's confusing, but that is a bad reason to not use something. By the same logic we shouldn't use regular expressions, range operators ('..' and the seemingly unknown "flip-flop" variation). They're powerful when used correctly, so we should learn to use them correctly.

Why have you put brackets around true?

Consider the OP's example:

<% question = question.size > 20 ? question.question.slice(0, 20)+"..." : question.question %>

Wrapping the conditional test helps make it more readable because it visually separates the test:

<% question = (question.size > 20) ? question.question.slice(0, 20)+"..." : question.question %>

Of course, the whole example could be made a lot more readable by using some judicious additions of whitespace. This is untested but you'll get the idea:

<% question = (question.size > 20) ? question.question.slice(0, 20) + "..." \
                                   : question.question 

Or, more written more idiomatically:

<% question = if (question.size > 20)
                question.question.slice(0, 20) + "..."

It'd be easy to argument that readability suffers badly from question.question too.

Difference between "and" and && in Ruby?, if statement and or operator to print false statements because if statement and or operator always works on true condition. Here else block is executed when the given condition is true. puts "Welcome!" puts "Hello!" I graduated 5 months ago and was trying to get a job in the Software industry, I found out about Learnvern and started Software Testing course in a week I had completed the course and appeared for 3 job interviews and landed a job as a software tester.

A simple example where the operator checks if player's id is 1 and sets enemy id depending on the result

player_id==1? enemy_id=2 : enemy_id=1
# => enemy=2

And I found a post about to the topic which seems pretty helpful.

Ruby, Conditional Operator in Ruby. It evaluates the CONDITION. If it is true then the code evaluates the part between ? and : and returns the result. If the CONDITION is false, then the middle part is skipped and the 3rd part is evaluated and the result of that expression is returned. Conditional operators are used to evaluate a condition that's applied to one or two boolean expressions. The result of the evaluation is either true or false. The result of the evaluation is either true or false.

Ruby, Refactoring if-else statements with the ternary operator (? :) programming language, but for the purpose of showing it's use I will be demonstrating on Ruby. A conditional is a fork (or many forks) in the road. Your data approaches a conditional and the conditional then tells the data where to go based on some defined parameters. Conditionals are formed using a combination of if statements and comparison operators (<, >, <=, >=, ==, !=, &&, ||).

The conditional operator in Ruby, the conditional operator (? :) in Ruby? How is the conditional operator (`? :`) used in Ruby?For example, is this correct? 20 ? question.question.slice(0, 20)+". You can overwrite what they do & use them to define custom behavior in your own classes. For example, by defining == you can tell Ruby how to compare two objects of the same class. Now: Let’s go over a few examples so you can get a solid overview of how these Ruby operators work & how to use them in your code.

Refactoring if-else statements with the ternary operator (? :), 129 Using the Ternary Operator The ternary operator (? :) is yet another way to set up conditional logic. It allows you to compare the values of two different  Ruby Ternary Operator. There is one more operator called Ternary Operator. It first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation. The conditional operator has this syntax −