0

I'm trying to achieve an array that is a collection of the first element of each row achieved by reading a CSV file.

I have the following:

ids = []
CSV.foreach(filename) do |row|
  ids << row[0]
end
ids

Is there any way to write this in one line? Or neater than that?

3
  • What do you expect to be the result of reading without it being an array? Does that make sense? Commented Sep 14, 2018 at 9:44
  • If there's a better way to approach it please let me know. My only end aim is to return an array made of the first element of each row of the CSV Commented Sep 14, 2018 at 9:45
  • 1
    CSV.foreach(filename).map(&:first) should work. Commented Sep 14, 2018 at 11:05

2 Answers 2

2

ids = CSV.read(filename).map(&:first)

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

4 Comments

Works perfectly - many thanks will accept when I can (not sure who downvoted you)
Your edit after my answer made your answer look essentially the same as mine.
@sawa using read over foreach was an improvement but it didn't answer the full question of getting the first element and assigning the value to ids.
"using read over foreach was an improvement"read parses the entire file into an array, whereas foreach reads it row by row. The latter is probably more memory efficient, especially for huge CSV files.
0

Simply do:

CSV.read(filename)

If you wanted to collect only the first column, then:

CSV.read(filename).map{|row| row[0]}

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.