In Ruby, I have an array of simple values โโ(possible encodings):
encodings = %w[ utf-8 iso-8859-1 macroman ]
I want to keep reading the file from disk until the results are valid. I could do this:
good = encodings.find{ |enc| IO.read(file, "r:#{enc}").valid_encoding? } contents = IO.read(file, "r:#{good}")
... but, of course, this is stupid, as it reads the file twice for good encoding. I could program it in a crude procedural style as follows:
contents = nil encodings.each do |enc| if (s=IO.read(file, "r:#{enc}")).valid_encoding? contents = s break end end
But I want a functional solution. I could do it so functionally:
contents = encodings.map{|e| IO.read(f, "r:#{e}")}.find{|s| s.valid_encoding? }
... but, of course, it saves files for each encoding, even if the first was valid.
Is there a simple template that is functional, but does not continue to read the file after the first success?
source share