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:
- In Terminal, I go to the place I want to store my directory: cd /Users/rachel/dev
- I Make a new directory, which will contain a directory of my images, as well as a Ruby file: mkdir “EmojiFinder”
- I change into the EmojiFinder directory: cd EmojiFinder
- I make a ProfileImages directory, where I’ll put my images: mkdir “ProfileImages”
- I change into the ProfileImages directory and copy in my photos: cp /Users/rachel/Desktop/emoji_mini.png /Users/rachel/dev/ProfileImages
- I change back into my EmojiFinder directory: cd ..
- 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.
- Ruby Class: Dir documentation
- Working with directories YouTube video by NeatIt
- Basic File and Directory Operations in Ruby by RichOnRails
- Terminal Cheat Sheet for Mac