Painlessly Remove All Ruby Gems on Windows
If you want to uninstall all gems from your local Ruby installation on a Linux, Unix or MacOSX box then you can rely on the standard shell commands like “cut” and “xargs”, to make the process easy and effortless. The command itself is a one liner as follows:
gem list | cut -d" " -f1 | xargs gem uninstall -aIx
Read this post titled — Painlessly Remove All Ruby Gems — to learn the details. If you are on Windows though, the usual “cut” and “xargs” are not available. What are the alternatives then? One old school method may be to write a batch file or a script to do the job. However, that method is both a bit clumsy and verbose for a task that could be achieved through a one liner elsewhere. A smarter option then is to use the Windows PowerShell. Lets see how.
First start a PowerShell instance. If you are on Windows 7, it would simply mean typing “PowerShell” (or even “powershell”) on your program search box and then selecting the “Windows PowerShell” program. Once a session is instantiated, type the usual
gem list
command to list all the installed gems. On my machine the output looks like so:
To get a list of all installed gems, one unique entry per line, and containing nothing other than the names one can use the “cut” command on a Unix/Linux/MacOSX machine. With PowerShell though
gem list | cut -d" " -f1
doesn’t work but
gem list | %{$_.split(' ')[0]}
does. The $_ passes the current variable value to the “split” command, which uses a delimiter to split a string. In the example above a space is the delimiter. The parts generated out of the splitting are available as members of an array. Accessing the element at the 0th index of this array returns the first element.
Now that we have the names of all the installed gems, we need to iterate over this list and invoke gem uninstall with flags Iax for each of these. The I is for ignore dependency, a is for all matching gems and x is for no confirmation required. In other words running
gem uninstall -Iax activerecord
should uninstall all gems matching the name — “activerecord” — without any required confirmation. Using xargs it is easy to pass the current value to a command as one iterates over a list. However, running
gem list | cut -d" " -f1 | xargs gem uninstall -aIx
doesn’t get the job done as xargs is unknown to PowerShell. Don’t be disappointed though for PowerShell has a replacement for xargs and its an elegant one. The position of the $_ makes all the difference. So the one liner that removes all ruby gems is:
gem list | %{$_.split(' ')[0]} | %{gem uninstall -Iax $_ }
Isn’t that nice, simple and just a one liner!
Leave a Comment