require 'tmpdir' Dir.mktmpdir("my-prefix") do |dir| File.open(File.join(dir,"text.txt"), 'w') do |f| f.write("this is a test") end end
IO.write("/path/to/file.txt", "This is my cool text I need to write! Yay!") contents = IO.read("/path/to/file.txt")
If you forget to do this you will have to wait until the GC runs or your process goes away.
file = Tempfile.new ## do stuff and not close/unlink, leaked!
StringIO does everything Tempfile does other than having a path but does not require unlinking, closing or any cleanup.
It's just winning all over the place.
path = File.join("Users", "mauricio", "projects", "ruby")
Is not the same as:
path = ["Users", "mauricio", "projects", "ruby"].join(File::SEPARATOR)
- root - lib - my_gem - operation.rb - config - items.yml
my_gem_directory = File.dir(__FILE__) # or __dir__ if you're on Ruby 2.x File.join(my_gem_directory, "..", "..", "config", "items.yml")
file = File.open("some-file.ext", "w") file.write("hey, this is bad!") file.write("where's the exception handling code?") file.close
File.open("some-file.txt", "w") do |f| f.write("this is some text\n") f.write("and some more text") end
require 'pathname' path = Pathname.new("README.markdown") puts path.extname => ".markdown" full_path = path.expand_path => Pathname:/Users/mauricio/projects/ruby/mauricio.github.com/README.markdown puts full_path.dirname => Pathname:/Users/mauricio/projects/ruby/mauricio.github.com