Mark
Mark

Reputation: 6455

Better way of creating an array and pushing values

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?

Upvotes: 0

Views: 60

Answers (2)

sawa
sawa

Reputation: 168131

Simply do:

CSV.read(filename)

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

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

Upvotes: 0

Ben Toogood
Ben Toogood

Reputation: 479

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

Upvotes: 2

Related Questions