Saturday, September 6, 2014

Some Quick Late Night Ruby Fun

I should be asleep, but I'm not. Instead I'm up hacking around with ruby, taking some online classes, and generally having a good time.
In an effort to train myself in one discipline, I'm taking some online classes for ruby/ruby on rails/webdevelopment.

The kids and wife have all gone to bed, so I went through a course level about the ActiveSupport library, and started playing around in IRB with what I had learned. Eventually I found myself exercising one of my favorite ruby "koans" : writing a list of the gems I have installed on my computer into a text file. In the past I wrote this as a script that I would execute shortly before system updates or new ruby builds, so I can quickly install the ruby gems I use.

One of the things I've always wanted to do is "get it on one line" of ruby code. I started by executing the following in irb:

`gem list`

The backticks around gem list tell the interpreter "Go to your native environment (bash in this case) and execute the command gem list". The result is  a list of gems, including all the current versions installed, listed like so:

"twitter (5.11.0, 5.10.0, 5.9.0)\ntzinfo (1.2.2, 1.2.1, 1.1.0)\nuglifier (2.5.3, 2.5.1, 2.5.0)\nwatchr (0.7)\nxpath (2.0.0)\nyajl-ruby (1.2.1)\nzip (2.0.2)\n"

That's cool, but I don't necessarily need to know the versions. So the next step was to remove the versions from gems. I needed a regex and gsub to do that.

`gem list`.gsub(/\s[(].*[)]/, "")

this means, "Give me a string where we substitute everything in between two sets of parentheses including the parentheses and the space in front of the opening parenthesis, with an empty string."
That gave me something that looked like:


This gave me a single string of the list of gems installed. I then rediscovered how to open a file and properly write to the file. Several iterations of using do blocks later, I decide to go ahead and use the script below to write the file all in one line:"gemlist.txt", "w") {|file| file.write `gem list`.gsub(/\s[(].*[)]/, "")}
Now when I use a text editor to view gemlist.txt I see this:


And more importantly, I can use ruby to parse the file, and reload the gems I need to reinstall next time I build ruby!

The end!

Post a Comment