10

我想在字符串中放置一个变量,但也对变量有一个条件

就像是:

x = "best"

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

我可以在字符串之外做y||x。我在字符串中做什么?

4

3 回答 3

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

或者

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

或者

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

你可以y||x像在它外面一样使用内部插值

于 2012-11-25T19:49:36.773 回答
4

你绝对可以在一个字符串中做同样的事情

y = nil
x = "best"

s = "This is the #{y || x} question"
s # => "This is the best question"
于 2012-11-25T19:50:14.410 回答
2

使用三元运算符:

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

于 2012-11-25T19:51:34.773 回答