在字符串连接中,是否可以直接在语句中包含条件?
在下面的示例中,我希望仅当 dear
列表不为空时才连接 "my dear"
。
dear = ""
string = "hello" + " my dear" unless dear.empty? + ", good morning!"
但是结果报错:undefined method '+' for true
我知道另一种方法是在这条语句之前定义一个额外的变量,但我想避免这种情况。
最佳答案
使用插值而不是连接更容易和更具可读性:
dear = ""
string = "hello#{ ' my dear' unless dear.empty? }, good morning!"
关于Ruby:如何将条件插入字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28648536/