Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...