steve_gallagher steve_gallagher - 5 months ago 16
Ruby Question

Trying to open a file in Ruby - Getting TypeError: can't convert String into Integer

Not sure whats going on here, or what could be the integer in this case. Here's the code:

def build_array_from_file(filename)
contents = []
File.read(File.expand_path('lib/project_euler/' + filename), 'r') do |file|
while line = file.get
contents << line
end
end
contents
end


filename is a string and I've checked to make sure the path comes up valid.

Any thoughts? Thanks.

Answer

File.read has no second argument for mode nor block, that's File.open:

contents_string = File.read(File.expand_path('lib/project_euler/' + filename))

Note that you can also write:

contents = File.open(path).lines # returns a lazy enumerator, keeps the file open

Or:

contents = File.readlines(path) # returns an array, the file is closed.