Curious_Bop Curious_Bop - 2 months ago 5
Ruby Question

ruby split initial file contents into array

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


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

test ='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 ='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



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

txt =<<_

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


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


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).