In the string "#{x ? (x.to_s + ' is ') : ''}ok", Rubocop's Style/StringConcatenation suggests avoiding the +. But that requires a nested string interpolation "#{x ? '#{x.to_s} is ' : ''}ok)", which at least in Ruby 2.7 is not expanded: #{x.to_s} is treated like any other literal.
"#{x ? (x.to_s + ' is ') : ''}ok"
+
"#{x ? '#{x.to_s} is ' : ''}ok)"
#{x.to_s}
Is the + version alright because it's on the fringes of what a style guide could cover, or must one introduce a temporary variable?
tmp = x ? '#{x.to_s} is ' : '' "#{tmp}ok"
Context: the string is sent to a logfile. ok is actually a long list of details. x is worth logging, but only when it exists.
ok
x
Yes, a variable will make this more readable (imo):
prefix = "#{x} is " if x "#{prefix}ok"
(this relies on the fact that nil#to_s == '')
nil#to_s == ''
2.1m questions
2.1m answers
60 comments
57.0k users