开发者

Load a single-column CSV file into a Ruby array

开发者 https://www.devze.com 2023-03-22 09:17 出处:网络
I am new to Ruby. Below is my naive code to loa开发者_Go百科d a single-column CSV file into a Ruby array.

I am new to Ruby.

Below is my naive code to loa开发者_Go百科d 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


Try this:

require 'csv'
countries = CSV.read("#{RAILS_ROOT}/config/countries.csv").flatten
0

精彩评论

暂无评论...
验证码 换一张
取 消