I have started including an executable in my project setup. Many of the code challenges I have been practicing lately have included file I/O, and while TDD and code exercising with RSpec is still my main process, developing a stand-alone fully-functional project requires something more.
Blocks Code Challenge
I found the blocks code challenge on the UVa code competition website. To sum up, you have to write a program that will parse and carry out a series of commands for stacking blocks.
- move a onto b
- move a over b
- pile a onto b
- pile a over b
- quit
The commands will be provided in an input file, and an output is specified. Fun problem, right? So, I start my project folder using my thor task, and work awhile adding logic and tests and data as appropriate. My file tree finishes like this:
blocks
├── data
│ ├── input.txt
│ └── output.txt
├── lib
│ └── blocks.rb
├── spec
│ ├── blocks_spec.rb
│ └── spec_helper.rb
├── Gemfile
└── README.mdSo, in order to use my script, I would have to call it from the command line:
$ ruby lib/blocks.rb data/input.txt
#=> or
$ data/input.txt | ruby lib/blocks.rbThis is an extremely verbose way to deliver a final product, and I would much rather call $ blocks <file_input>. It turns out that making an executable is easy and elegant, just like everything else in ruby. You just have to declare the ruby environment, include a few notes on usage, load the file tree, and call the class:
#!/usr/bin/env ruby
# blocks
# 10-Sep-2013
#
# Usage:
# ./blocks data/input.txt
#
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), 'lib'))
require 'blocks'
Blocks.new.process_inputPlacing this code in a non-extension file, like ‘blocks’, in the main directory, I can make it an executable by changing the file permissions:
$ chmod +x ./blocksAnd I can call it like any other executable:
$ ./blocks data/input.txtI liked this solution so much, I added it to my thor project setup! Oh, and if you are interested in seeing my solution for the blocks problem, checkout my github repo
Awesome.