How to enable condition inside string in ruby

I want to put a variable in a string, but also have a condition for the variable

something like:

x = "best" "This is the #{if !y.nil? y else x} question" 

outside the line i can do y||x . what should i do inside the string?

+7
source share
3 answers
 "This is the #{y.nil? ? x : y} question" 

or

 "This is the #{y ? y : x} question" 

or

 "This is the #{y || x} question" 

you can use y||x inside interpolation, as well as outside it

+14
source

You can absolutely do the same in the line

 y = nil x = "best" s = "This is the #{y || x} question" s # => "This is the best question" 
+4
source

Use the ternary operator:

"This is the #{!y.nil? ? y : x} question"

+2
source

All Articles