如何改进用```引用所有数组元素的代码并返回一个包含所有引用和逗号分隔元素的字符串?

Bac*_*cko 9 ruby arrays ruby-on-rails collect

我正在使用Rails 3.2.2,我想引用所有数组元素'并返回一个包含所有引用和逗号分隔元素的字符串.这时我正在使用

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

但我认为我可以改进上面的代码(可能是通过使用一个未知的Ruby方法,如果它存在).可能吗?

Sig*_*urd 11

我用

"'#{%w{a b c}.join("', '")}'"
Run Code Online (Sandbox Code Playgroud)

这是扩展版本:

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


N.N*_*.N. 6

您可以collect使用其别名map.join等效替换*.最后,你可以使用快捷键编写字符串数组,%w(...)和您可以使用单引号的参数.join/ *因为它不使用字符串插值(不过,如果它最好也可能是有问题的,当涉及到性能).

%w(a b c).map {|x| "'#{x}'"} * ', '
Run Code Online (Sandbox Code Playgroud)

看来这个版本与原版没有性能差异,但Sigurd的版本表现更好:

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)

基准代码:

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
Run Code Online (Sandbox Code Playgroud)