Ruby: Using Directories

Until this past week, my coding hadn’t expanded much past a repl environment. Last Monday, that changed very quickly because I started an immersive web development program at the Flatiron School.

My first week at Flatiron expanded my scope far beyond coding in my beloved repl.it environment. I was using tools like Terminal and the text editor Sublime Text to do things like interact with directories. Here’s how to use Terminal, explained a bit in an earlier post, and a text editor such as Sublime to create a directory and then output an array of files from it.

A directory is a collection of files (maybe music files or photos, for example) that can be accessed from a Ruby method. Ruby methods Dir.entries and Dir.foreach use the directory file path to return file names:

Let’s pretend I want to create a directory filled with images I could use as profile photos. Some of the files are jpegs and others are pngs (of fun, customizable emojis that I design on madewithcode.com.) I’m going to build a method that will access my ProfileImages directory and output only files with a .png extension:

  1. In Terminal, I go to the place I want to store my directory: cd /Users/rachel/dev
  2. I Make a new directory, which will contain a directory of my images, as well as a Ruby file: mkdir “EmojiFinder”
  3. I change into the EmojiFinder directory: cd EmojiFinder
  4. I make a ProfileImages directory, where I’ll put my images: mkdir “ProfileImages”
  5. I change into the ProfileImages directory and copy in my photos: cp /Users/rachel/Desktop/emoji_mini.png /Users/rachel/dev/ProfileImages
  6. I change back into my EmojiFinder directory: cd ..
  7. I create a ruby file: touch “EmojiFinder.rb”

This method outputs an array of files from ProfileImages directory. From there, I could iterate through the array, outputting only files that contain the .png extension, but I think I’ll solve this a little differently.

This method iterates through the files in the directory, and will only output files with a .png extension. I called the method using the file path to the ProfileImages directory.

Et voila! Running ruby EmojiFinder.rb in Terminal outputs all image files with a .png extension.

Helpful resources:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s