Curious_Bop Curious_Bop - 4 months ago 13
Ruby Question

ruby split initial file contents into array

I have a file that I am reading that follows the following format:

12345,500,500
23456,100,150
34567,99,109


What I'm trying to do is read up until the first comma of the file and then map them into an array.

test = File.read('results.txt').split(',')[0]
p test
=> "12345"


would return me back the first value before the comma but I want to put all of them into an array

test = File.read('results.txt').split(',')[0].map(&:strip)


I have tried the following above and other similar permutations but unfortunately it's not quite the right it seems.

my desired result is to have an array of the following

[12345,23456,34567]

Answer

Here are a couple of ways to do that. First create the file.

txt =<<_
12345,500,500
23456,100,150
34567,99,109")
_

FName = "tmp"
File.write(FName, txt)
  #=> 43

#1

File.foreach(FName).map { |line| line[0, line.index(',')] }
  #=> ["12345", "23456", "34567"]

#2

File.foreach(FName).map { |line| line.to_i.to_s }
  #=> ["12345", "23456", "34567"]

IO#foreach reads the file line-by-line, as contrasted by IO#readlines, which "gulps" the entire file into an array. foreach is therefore less demanding of memory than readlines. You can write either IO.foreach... or File.foreach... as File is a subclass of IO (File < IO #=> true).