Reputation: 38902
I have an array of string which contains the "firstname.lastname" strings:
customers = ["aaa.bbb", "ccc.ddd", "www.uuu", "iii.oooo", ...]
Now, I would like to transfer each element's string format in the array by removing the "." and use space instead. That's I want the array to be:
customers = ["aaa bbb", "ccc ddd", "www uuu", "iii oooo", ...]
What is the most efficient way to do it?
---------------- MORE -------------------
And how about my case here
Upvotes: 0
Views: 1644
Reputation: 4051
customers.collect!{|name| name.gsub(/\./, " ")}
Update
@tadman has it, here's my benchmarking 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
Upvotes: 7
Reputation: 211740
You can always just modify each value in-place:
customers.each { |c| c.gsub!(/\./, ' ') }
The alternatives, like collect!
are more appropriate when you're switching the kind of object, not just altering the content of an existing object.
Note that this will mangle the original input, so if the String values in customers
are frozen or need to be preserved in their initial form this won't work. This is probably not the case, but it is important to keep this in mind.
Update: After some benchmarking I've come to the conclusion that the fastest way to perform this operation is:
customers.each { |c| c.tr!('.', ' ') }
For those that are curious, here's a benchmark scaffold to experiment with.
# 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!('.', ' ') }
Upvotes: 2
Reputation: 17735
Don't know if this is the most efficient, but it does the job:
customers.collect!{ |name| name.split('.').join(' ') }
Upvotes: 2