patternrubyMinor
Splitting an array at commas
Viewed 0 times
arraycommassplitting
Problem
I was given a file of size 46KB full of names (around ~5000), in the format as shown below:
I wonder if my code below is optimal in doing what I want, which is to translate this txt file into an array of names.
"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH"..."DARRELL","ALONSO"I wonder if my code below is optimal in doing what I want, which is to translate this txt file into an array of names.
array = []
File.readlines('names.txt').each do |l|
array << l.delete("\"").split(",")
end
array.flattenSolution
Yes it is, it takes 0.372798 seconds to run on my computer for a 50 MB file, for a 46KB file this runs in the blink of an eye.
Anyway as this is Codereview I suggest an equally fast but higher level version of your code:
Anyway as this is Codereview I suggest an equally fast but higher level version of your code:
def get_names(filename)
File.read(filename).tr('"', '').split(',')
endCode Snippets
def get_names(filename)
File.read(filename).tr('"', '').split(',')
endContext
StackExchange Code Review Q#86120, answer score: 3
Revisions (0)
No revisions yet.