DEV Community

Burdette Lamar
Burdette Lamar

Posted on

Why I Love Coding in Ruby: Dir.mktmpdir

Because blocks!

This code creates a temporary directory and a file foo.txt therein:

require 'tmpdir'

Dir.mktmpdir do |dir|
  open("#{dir}/foo.txt", 'w') do |file|
    # Do something with the file.
  end
end

When the block exits, the directory and its contents are deleted automatically.

Easy peasy!

Top comments (4)

Collapse
 
ben profile image
Ben Halpern

Thing of beauty

Collapse
 
mountainmanjon profile image
Jon Luke Harvey • Edited

What is your opinion on Ruby scripting verses other languages like Python or Bash? I know that Metasploit (vulnerability application) is programmed in ruby but I also have read that most people use Python or Bash for scripting. What are some advantages Ruby might have?

Collapse
 
burdettelamar profile image
Burdette Lamar

I don't think of Ruby as a scripting language, even though it's interpreted rather than compiled. In fact, I never say 'test script' b/c it seems to me to suggest something lightweight rather than substantial.

Bash is not object-oriented (disqualifying in my view), and therefore not at all comparable to Ruby, Python, or even Perl, all of which are object-oriented.

Besides blocks (which I love), Ruby just feels fluid to me.

Collapse
 
mountainmanjon profile image
Jon Luke Harvey

Thanks for your honest response! :) I will keep that in mind for sure.