1

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]
3
  • 1
    What exactly is your desired result? Commented Aug 3, 2016 at 19:09
  • Updated question with my desired result. Commented Aug 3, 2016 at 19:12
  • In the first instance you say you want a single string ("12345"). Later you say you want an array of three integers. Which is it? In any event, if you want an array containing the first part of every line, that obviously gives you the first part of the first line, so I don't understand why the question even mentions the first line. Commented Aug 3, 2016 at 21:04

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.