質問

Ruby's CSV.foreach('file.csv', headers: true) returns an enumerator, but I can't seem to call any enumerable methods on it, i.e. I can't call CSV.foreach('file.csv', headers: true).map(&:to_hash) or even CSV.foreach('file.csv', headers: true).to_a. This is unexpected behavior, as I can call these methods on other enumerators like 1.upto(5).to_a etc. What's the explanation for this?

役に立ちましたか?

解決

Take a look at the source here. At the time of writing, CSV::foreach is defined as

def self.foreach(path, options = Hash.new, &block)
  open(path, options) do |csv|
    csv.each(&block)
  end
end

so the each enumerator is enclosed within the open block and the method returns nil. If you want to interact w/ the enumerator you can do something like

CSV.open('file.csv') do |csv|
  csv.each.map do |row|
    # whatever
  end
end
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top