billv wrote:I agree Ruby: I don't recognize that file or directory without the backslashes either...
That's one you have to watch out for in Ruby - there's a difference between "double-quoted" and 'single-quoted' strings when the code gets parsed by Ruby.
In double-quoted strings, the backslash gets read as an escape character - so that you can write things like "\n" for new-line, and "\t" for tab. "\N" and "\D" don't represent anything special, so the escapes just get ignored in your example.
Inside double's you can also write things like...
"The value of my variable is #{@my_variable}"...to insert calculated values into strings (the #{ represents the start and } the end of the substitution). Even whole expressions will work like that...
"Ten plus twelve equals #{10+12}"
Single quoted strings are always taken literally with no escapes or substitutions - so it's best to use single quotes around filenames/paths written into the code.
(NB - single quoted are also slightly faster to process because there are no special characters for Ruby to look out for.)
Your little code also contains a cardinal sin of file operations - assuming the file is found, you have opened it, but haven't closed it. That can lead to all sorts of problems, as access will then be denied to any other process/app' that needs to use the file. Closing also ensures that Windows clears any buffered data and writes it to the file.
Assuming it's just strings that you want to load and save, the easiest way is...
To read a string...
File.read('path') ...or...
File.read('path', start_position, length) - to read only part of a file.
That will return a String. Or you might prefer File.readlines('path') - which gives you a String array containing each line in turn.
Both of these methods sort out the opening and closing for you, so there's no need to worry about accidentally leaving files open.
To write a string...
A bit more tricky as you do need to explicitly open the file...
Code: Select all
my_file = File.open('path', 'w')
my_file.write(my_string)
my_file.close
You can put as many sequential writes between the open and close as you like.
There's also a slightly more compact version that uses a 'do...end' code block...
Code: Select all
File.open('path', 'w') do |my_file| # All of this bit must be on one line of code
my_file.write(my_string)
end
The do...end version is usually preferred because it also closes the file for you after the 'end', so you're less likely to end up with an accidentally open file due to a code typo'.
You'll see in both of them that you have to store the reference to the file in a local variable (e.g. 'my_file')
If you didn't see the 'read' and 'write' methods when you looked through the Ruby API - don't worry, your not going mad. 'File' is a sub-class of the
'IO' class of objects that can handle all sorts of other input/output operations - so most methods from the 'IO' class will also work for files.