2

I am new to Ruby.
Below is my naive code to load a single-column CSV file into a Ruby array.

QUESTION: Is there something better?
In particular, how to not hard-code the number of items?

require 'csv'
COUNTRIES = Array.new(240)
i = 0
CSV.foreach "#{RAILS_ROOT}/config/countries.csv" do |country|
  COUNTRIES[i] = country[0]
  i = i + 1
end

1 Answer 1

6

Try this:

require 'csv'
countries = CSV.read("#{RAILS_ROOT}/config/countries.csv").flatten
Sign up to request clarification or add additional context in comments.

1 Comment

+1. If the CSV has trailing commas after the one column an extra .compact at the end will be necessary.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.