IO
IO operations should be done within begin-rescue blocks.
Reading
contents = IO.read(portname) # The entire file will be read into memory as its contents is retrieved. Read closes after use.
contents = File.read(portname) # Same as above (File is a subclass of IO).
contents = File.open(filename, 'r') {|f| f.read } # Allows options to be passed e.g. b for binary. Use of a block ensures file is closed.
Note: A portname is different to a filename and can not contain arbitrary characters i.e. some characters have extra meaning. See Class: IO (Ruby 1.9.3).
Writing
File.open(filename, 'w') {|f| f.write(contents) } # Use of a block ensures file is closed.
References
- Class: IO (Ruby 1.9.3)
- Class: File (Ruby 1.9.3)
- Ruby - Convert File to String
- ruby: all ways to read from file
- Read entire file - Rosetta Code
Parsing UK dates
If you try to parse a date/time in the form ‘dd/mm/yy hh:mm:ss’ in Ruby 1.8.7, you can get the following:
irb(main):005:0> s = '14/02/07 20:54:19'
=> "14/02/07 20:54:19"
irb(main):006:0> Time.parse(s)
ArgumentError: argument out of range
from /usr/lib64/ruby/1.8/time.rb:184:in `local'
from /usr/lib64/ruby/1.8/time.rb:184:in `make_time'
from /usr/lib64/ruby/1.8/time.rb:243:in `parse'
from (irb):6
This is because it’s expecting mm/dd/yy (why anyone would want to use such a ridiculous format is anyone’s guess).
Block comments
=begin
Everything until =end is a block comment
=end