Reputation: 32190
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
Reputation: 1271
Use the ternary operator:
"This is the #{!y.nil? ? y : x} question"
Upvotes: 2
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
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