How to improve code that quotes all array elements with `'` and returns a string containing all those quoted and comma-separated elements?

一曲冷凌霜 提交于 2020-01-12 14:23:24

问题


I am using Rails 3.2.2 and I would like to quote all array elements with ' and return a string containing all those quoted and comma-separated elements. At this time I am using

['a', 'b', 'c'].collect {|x| "'#{x}'"}.join(", ")
# => "'a', 'b', 'c'"

but I think I can improve the above code (maybe by using a unknown to me Ruby method, if it exists). Is it possible?


回答1:


I use

"'#{%w{a b c}.join("', '")}'"

Here is expanded version:

' # Starting quote
%w{a b c}.join("', '") # Join array with ', ' delimiter that would give a', 'b', 'c
' # Closing quote



回答2:


You can replace collect with its alias map and .join with the equivalent *. Finally, you can use the shortcut for writing an array of strings, %w(...), and you can use single quotes for the argument of .join/* as it does not use string interpolation (though it may be questionable if it preferable when it comes to performance).

%w(a b c).map {|x| "'#{x}'"} * ', '

It appears there is no performance difference between this version and the original but that that Sigurd's version is performing better:

Original  3.620000   0.000000   3.620000 (  3.632081)
This  3.640000   0.000000   3.640000 (  3.651763)
Sigurd's  2.300000   0.000000   2.300000 (  2.303195)

Code for benchmark:

require 'benchmark'

n = 1000000

Benchmark.bm do |x|
  x.report("Original") { n.times do
      ['a', 'b', 'c'].collect {|x| "'#{x}'"}.join(", ")
    end}
  x.report("This") { n.times do
      %w(a b c).map {|x| "'#{x}'"} * ', '
    end}
  x.report("Sigurd's") { n.times do
      "'#{%w{a b c}.join("', '")}'"
    end}
end


来源:https://stackoverflow.com/questions/10647327/how-to-improve-code-that-quotes-all-array-elements-with-and-returns-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!