Curious_Bop
Curious_Bop

Reputation: 311

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]

Upvotes: 1

Views: 94

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110755

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

Upvotes: 1

koffeinfrei
koffeinfrei

Reputation: 2065

File.readlines('results.txt').map { |line| line.split(',') }.map(&:first)
=> ["12345", "23456", "34567"]

Upvotes: 0

Related Questions