2012-11-25 125 views
7

字符串我想将一个字符串中的变量中的条件,同时也对可变如何包括红宝石

类似的情况:

x = "best" 

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

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

回答

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

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

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

可以使用y||x内插值就像外面

4

您可以绝对做一个字符串中相同

y = nil 
x = "best" 

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

使用三元运算:

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