search&replace 2.0 or refactoring with ruby

sometimes i need to refactor some code in a file. until today i usually used search and replace along with some regular expressions, which more or less worked because i’m not exactly a pro regexp developer. (anyone? :) )

so, today i had to refactor something like this: i had a big array of arrays and wanted to convert it into a hash:

[[1, ‘buy car’], [2, ‘buy house’], [3, ‘plant tree’]]

should become

{1 => ‘buy car’, 2 => ‘buy house’, 3 => ‘plant tree’}

okay, this example is actually made up, that’s not what i was working on today. anyway, so as i said you could go and do some regex replace, which in this case wouldn’t bee too hard, but this is just a simple example. the new way i found for me is this: since the text is executable code already, why not execute it in order to transform itself? add a bit here and there and off we go:

puts [[1, ‘buy car’], [2, ‘buy house’], [3, ‘plant tree’]].map {|key,value|
“#{key} => ‘#{value}’ “}.join(”,\n”)

now if you are using TextMate all you have to do is press [apple]+[r] which will execute your code (make sure you have set your editing window to ruby) and there is your new hash table. sweet, isn’t it?

Tags:

Leave a Reply