Reputation: 671
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
Reputation: 2140
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
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
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
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