Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

ruby: workarounds for nested string interpolation

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.

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.

question from:https://stackoverflow.com/questions/65850119/ruby-workarounds-for-nested-string-interpolation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 == '')


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...