Nick Ginanto
Nick Ginanto

Reputation: 32190

How to include a condition inside a string in ruby

I want to place a variable within a string, but also have a condition on the variable

something like:

x = "best"

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

outside the string I can do y||x. what do I do inside the string?

Upvotes: 11

Views: 9049

Answers (3)

jboursiquot
jboursiquot

Reputation: 1271

Use the ternary operator:

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

Upvotes: 2

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230561

You can absolutely do the same within a string

y = nil
x = "best"

s = "This is the #{y || x} question"
s # => "This is the best question"

Upvotes: 4

user904990
user904990

Reputation:

"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 just like outside it

Upvotes: 22

Related Questions