sqrcompass
sqrcompass

Reputation: 671

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.

Upvotes: 14

Views: 11908

Answers (4)

Jin Lim
Jin Lim

Reputation: 2140

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 >

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118271

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!"

Upvotes: 3

Rustam Gasanov
Rustam Gasanov

Reputation: 15791

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

dear = ""

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

Upvotes: 15

Amit Joki
Amit Joki

Reputation: 59252

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

Upvotes: 6

Related Questions