------------------------------------------------------------------------
Opens the file, optionally seeks to the given offset, then returns
_length_ bytes (defaulting to the rest of the file). +read+ ensures
the file is closed before returning.
IO.read("testfile") #=> "This is line one\nThis is line two\
nThis is line three\nAnd so on...\n"
IO.read("testfile", 20) #=> "This is line one\nThi"
IO.read("testfile", 20, 10) #=> "ne one\nThis is line "
def readFile(path)
value = ''
file = File.open(path, File::RDONLY)
while line = file.gets do
value += line
end
file.close
return value
end
I think the way line by line is not very efficiently.
Is there a shorter way to get the content of a file?
greetings
Dirk Einecke
Simple way is:
content = File.read(filename)
But if you should learn about blocks so the code you provided can be replaced with something like the following (because your code doesn't have exception handling to guarantee that file.close is called):
File.open(path, File::RDONLY){|file| #use file.gets or whatever in here, preferably using another block
}
2.
file = File.open(path, File::RDONLY)
value = file.read
file.close
3.
value = File.readlines(path).to_s
4.
value = File.readlines(path).join
What is the fastes way (for Ruby) and what should I use?
greetings
Dirk Einecke
In my opinion, number one is the best. The latter two only make sense
for line-based formats, and even in such cases it's easier to just read
it all in at once. Number two, I assume, is just like number one,
except you have to close it up yourself, which is annoying.