简体   繁体   中英

Ruby: how to insert a conditional into a string concatenation

In a string concatenation, is it possible to include a conditional directly into the statement?

In the example below, I want "my dear" to be concatenated only if the dear list is not empty.

dear = ""

string = "hello" + " my dear" unless dear.empty? + ", good morning!" 

But the result is an error: undefined method '+' for true

I know the alternative would be to define an additional variable before this statement but I would like to avoid this.

In this case, you would be better off using ternary operators.

string = "hello" + (dear.empty? ? "" : " my dear") + ", good morning!" 

The syntax goes like

condition ? if true : if false

It is easier and more readable with interpolation instead of concatenation:

dear = ""

string = "hello#{ ' my dear' unless dear.empty? }, good morning!"

Here is something cutie

dear = ""
"hello%s, good morning!" % (' my dear' unless dear.empty?)
# => "hello, good morning!"
dear = "val"
"hello%s, good morning!" % (' my dear' unless dear.empty?)
# => "hello my dear, good morning!"

I will share my solution.

2.7.0 :040 > dear = ""
2.7.0 :041 > string = "hello #{dear.empty? ? "World" : dear}, good morning!"
2.7.0 :042 > string
 => "hello World, good morning!"
2.7.0 :043 > dear = "Test"
2.7.0 :044 > string = "hello #{dear.empty? ? "World" : dear}, good morning!"
2.7.0 :045 > string
 => "hello Test, good morning!"
2.7.0 :046 >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM