HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Splitting an array at commas

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraycommassplitting

Problem

I was given a file of size 46KB full of names (around ~5000), in the format as shown below:

"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.flatten

Solution

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:

def get_names(filename)
    File.read(filename).tr('"', '').split(',')
end

Code Snippets

def get_names(filename)
    File.read(filename).tr('"', '').split(',')
end

Context

StackExchange Code Review Q#86120, answer score: 3

Revisions (0)

No revisions yet.