Tired of old-style Ruby hashes? Use vim?

Here ya go:

:%s/:\(\w\+\) => /\1: /g

You can also do cool stuff to run this across all buffers, tabs, etc. via something like this:

:tabdo %s/:\(\w\+\) => /\1: /g

You can even make it work with many non-buffer files at once from the command-line:

    vim -c "set hidden" \
        -c "set nomore" \
        -c "argdo %s/:\(\w\+\) => /\1: /ge | update" +qall \
           `find . -type f -name "*.rb" -or -name "*.html.erb"`

(though to be fair sed is probably a better choice if you’re not doing something super vim-specific)

And NOTE that this will not work well with hashes that use namespaced objects. The regex could certainly be tweaked for this specific use case, but it’s probably easier to just fix the few cases where this kind of thing doesn’t work. For me, it was just in my routes file where engines were mounted by stuff like mount Foo::Bar::Engine => '/blargh'.

So for all you fancy IDE users, how much pain would it be to do this sort of thing:

  • For one file
  • For all open files
  • For arbitrary files of a particular type or within a particular directory
  • For a specific set of lines within a file (say for modifying “license” type headers without worrying about breaking actual code)

Some can do it, sure, but rarely is it as quick a task as it is in vim. (Although to be fair, figuring out how to make it work in vim may not be so easy – but once you learn this kind of stuff, it’s amazingly useful)

If you don’t “get” the vim regex search and replace, though, you probably are indeed better off with your GUI IDE and your little sippy cup and blanket.

Oh, and you probably need to stop calling yourself a developer. Just a thought.


Little update: today I was convinced to hate 1.9 hashes, so I can’t really condone this code… but it’s still useful. I’m very torn right now. Damn it!

One Reply to “Tired of old-style Ruby hashes? Use vim?”

  1. I agree so much! Hashes are really great tool ulenss they are used as method parameters.I always try not to do that by defining methods with multiple “simple type” parameters, but…Do you know activedoc library? (https://github.com/iNecas/activedoc) in shortcut it allows you to define more info about method parameters (even gives some kind of error or exception, i dont remember which one, if parameter does not goes along with definition)For example if you have method def do_sth(param)…You can define that param must be hash which must have specific keys and value of each of them must have specific type. What do you think about it?

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.