Ruby数组:更改字符串元素格式

时间:2011-11-04 15:11:30

标签: ruby-on-rails ruby

我有一个字符串数组,其中包含“ firstname.lastname ”字符串:

customers = ["aaa.bbb", "ccc.ddd", "www.uuu", "iii.oooo", ...]

现在,我想通过删除“”并使用空格来传输数组中每个元素的字符串格式。那是我想要的数组:

customers = ["aaa bbb", "ccc ddd", "www uuu", "iii oooo", ...]

最有效的方法是什么?

---------------- MORE -------------------

我的案例here

怎么样?

3 个答案:

答案 0 :(得分:7)

customers.collect!{|name| name.gsub(/\./, " ")}

<强>更新

@tadman有,这是我的基准测试FWIW

require 'benchmark'

customers = []
500000.times { customers << "john.doe" }

Benchmark.bm do|b|
  b.report("+= ") do
    # customers.collect!{|name| name.gsub(/\./, " ")} # 2.414220
    # customers.each { |c| c.gsub!(/\./, ' ') } # 2.223308
    customers.each { |c| c.tr!('.', ' ') } # 0.379226
  end
end

答案 1 :(得分:2)

不知道这是否是效率最高的,但是它可以胜任:

customers.collect!{ |name| name.split('.').join(' ') }

答案 2 :(得分:2)

您可以随时修改每个值:

customers.each { |c| c.gsub!(/\./, ' ') }

当您切换对象类型时,替代方法(如collect!)更合适,而不仅仅是更改现有对象的内容。

请注意,这会破坏原始输入,因此如果customers中的字符串值被冻结或需要以其初始形式保留,则无效。情况可能并非如此,但重要的是要记住这一点。

更新经过一些基准测试后,我得出的结论是,执行此操作的最快方法是:

customers.each { |c| c.tr!('.', ' ') }

对于那些好奇的人,here's a benchmark scaffold要进行实验。

  #     user     system      total        real
  # 0.740000   0.020000   0.760000 (  0.991042)
  list.each { |c| c.gsub!(/\./, ' ') }

  # 0.680000   0.010000   0.690000 (  1.011136)
  list.collect! { |c| c.gsub(/\./, ' ') }

  # 0.490000   0.020000   0.510000 (  0.628354)
  list.collect!{ |c| c.split('.').join(' ') }

  # 0.090000   0.000000   0.090000 (  0.103968)
  list.collect!{ |c| c.tr!('.', ' ') }