DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Albert has posted 3 posts at DZone. View Full User Profile

Unix Shell Script Providing Ruby On Rails Enhanced String Methods

  • submit to reddit
        Assuming you have Rails installed as a gem, the following Unix shell script (which I named String, but you can name anything you want when you save the following into a file) allows you to call Ruby String methods (including, importantly, the methods that the Rails ActiveSupport extensions add) on an arbitrary number of arguments, and it will print out the results, e.g.,

$ String camelize snake_case_example another_snake_case_example

The output is:


#!/usr/bin/env ruby

if ARGV.size > 1 then
  gem 'activesupport'
  require 'active_support/core_ext/string/inflections'

  class String
    include ActiveSupport::CoreExtensions::String::Inflections

  command = ARGV.shift
  ARGV.each { |argument|
    puts argument.send( command )
  # Print usage information
  puts "Usage: #{File.basename( __FILE__ )} <command> <argument_1> [<argument_2> ...]"


Brandon Zylstra replied on Mon, 2007/11/19 - 11:51pm

It fails for me with an error message: {bash} $ ./String camelize blah_blah ./String:4: undefined method `gem' for main:Object (NoMethodError)

Albert Chou replied on Mon, 2014/03/31 - 9:04am in response to: Brandon Zylstra

I never noticed this comment until someone sent me an email referring to this snippet!

In case you haven't worked it out for yourself, you'll need to add the following line right after the "if ARGV.size" line:

require 'rubygems'

And of course you'll need RubyGems itself installed and then the ActiveSupport gem installed!